Update an Angular variable in the view

*爱你&永不变心* 提交于 2020-02-07 17:14:43

问题


I would like my output to read

0
01
012
0123
01234
etc...

I expected this simple code I wrote to do the trick, but instead it prints

01111111111 011111111111
02222222222 022222222222
03333333333 033333333333
04444444444 044444444444
05555555555 055555555555
06666666666 066666666666

Why is this happening?

This is my Angular code:

<div ng-app="App" ng-controller="ctrl">
     <div ng-repeat="num in [1, 2, 3, 4, 5, 6]">
         <label>{{previousNumber}}</label>
         {{previousNumber = (previousNumber + "" + num)}}
     </div>
</div>

And here's the JSFiddle: http://jsfiddle.net/fd1f6yso/2/


回答1:


When you both $watch - with {{previousNumber}} - and modify previousNumber with every evaluation of the expression {{previousNumber = (previousNumber + "" + num)}}, you get into an infinite loop - which Angular prevents after 10 iterations of $digest.

To achieve what you want, you'd need a variable in the outer scope of your ng-repeat to keep the increasing string, and a local variable in the child (inner) scope of each ng-repeat iteration created with ng-init:

<div ng-init="label = ''">
    <div ng-repeat="num in [1, 2, 3, 4, 5] track by $index" 
         ng-init="$parent.label = $parent.label+''+num; thisLabel = $parent.label">
        <label>{{thisLabel}}</label>
    </div>
</div>

You need to use $parent.label (instead of label) due to how prototypical inheritance of literals works.

It should be noted that while this is fine for an intellectual exercise, I would NOT recommend this in real development.

fiddle



来源:https://stackoverflow.com/questions/27590337/update-an-angular-variable-in-the-view

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!