本文介绍了更新视图中的 Angular 变量的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想读取我的输出

001012012301234等等...

我希望我写的这个简单的代码可以解决这个问题,但它打印出来

01111111111 01111111111102222222222 02222222222203333333333 03333333333304444444444 04444444444405555555555 05555555555506666666666 066666666666

为什么会这样?

这是我的 Angular 代码:

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

这里是 JSFiddle:http://jsfiddle.net/fd1f6yso/2/

解决方案

当你同时 $watch - 和 {{previousNumber}} - 并修改 previousNumber 每次对表达式 {{previousNumber = (previousNumber + "" + num)}} 进行评估时,您都会进入一个无限循环 - 在 $ 的 10 次迭代后,Angular 会阻止这种循环摘要.

要实现您想要的效果,您需要在 ng-repeat 的外部作用域中使用一个变量来保持不断增加的字符串,并在每个子(内部)作用域中使用一个局部变量ng-repeat 使用 ng-init 创建的迭代:

<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>

您需要使用 $parent.label(而不是 label),因为文字的原型继承是如何工作的.

应该注意的是,虽然这对于智力练习来说很好,但我不建议在实际开发中这样做.

小提琴

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/

解决方案

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

这篇关于更新视图中的 Angular 变量的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

09-15 13:35