更新视图的角度变量

更新视图的角度变量

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

问题描述

我想我的输出读

0
01
012
0123
01234
etc...

我希望这个简单的code我写了这样的伎俩,而是它打印

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?

这是我的角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>

和这里的的jsfiddle:

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

推荐答案

在两个 $观看 - 以 {{previousNumber} } - 并修改 previousNumber 与前pression {{previousNumber的每一个评价=(previousNumber ++ NUM)}} ,你进入一个无限循环 - 这角prevents后 $的10次迭代消化

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.

要达到你想要的,你需要在你的 NG-重复来保持增加字符串的范围外的孩子一个变量,局部变量是什么每一个(内)范围创建NG-重复反复NG-INIT

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>

您需要使用 $ parent.label (而不是标签),由于文字作品如何继承原型

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.

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

08-26 00:44