为什么不分配在角前pressions总是工作? [英] Why does assignment not always work in Angular expressions?
问题描述
我刚刚发现了什么是允许角前pressions这个有趣的明显不一致:
I just found this interesting apparent inconsistency in what is allowed in Angular expressions:
- 有可能在离pression 执行任务
- 这打破,如果转让涉及从ngRepeat 局部变量
- 这可以通过使用在控制器中而不是在恩pression分配所限定的设定器来克服
- It is possible to perform assignment in an expression
- This breaks if the assignment involves a local variable from an ngRepeat
- This can be overcome by using a setter defined in the controller instead of assignment in the expression
这是前pressions 似乎只明确禁止控件的文档流入前pressions,我没有看到实物上述行为的任何提及。
The docs on expressions seem only to explicitly disallow control flow in expressions, and I don't see any mention of the kind of behavior above.
我想从这个外卖是它可能仍要使用的setter一个更好的设计模式,但没有人知道是什么的前pressions可能更明确的参考呢?
I suppose the takeaway from this is it's probably a better design pattern to use a setter anyway, but does anyone know of a more definitive reference on what's possible in expressions?
也许,如果角单方面禁止他们分配会更好。 (A相关不一致的是,它似乎是可能在离pression递增其中i = i + 1的,但不是我+ = 1 ...)
Maybe it would be better if Angular unilaterally prohibited assignment in them. (A related inconsistency is that it seems to be possible to increment in an expression with i = i+1 but not with i+=1...)
推荐答案
这是在指令作用域的已知问题。你可以阅读的文章范围原型继承的细微差别,以了解更多关于作用域
的角度JS。
It is a known problem with scoping in directives. You can read the article The Nuances of Scope Prototypal Inheritance to know more about the scoping
in angular js.
这是一个孩子/ transcluded范围内的任何原始值赋值将创建一个新的实例值,而不是更改父范围值
Any primitive value assignment from a child/transcluded scope will create a new instance value instead of changing the parent scopes value
在你的情况你是一个原始值 selectedNumber
工作
In your case you are working with a primitive value selectedNumber
.
有两种建议的方式来解决这个问题。
There are two suggested ways to fix it
解决方法1
的使用对象,而不是原始值。的
Solution 1
Use a object instead of primitive value.
- 更改selectedNumber一个对象
scope.selectedNumber = {NUM:1};
- 更改显示器
< H2> {{selectedNumber.num}}< / H>
- 更改
NG-重复
点击处理程序NG-点击=selectedNumber.num =号
- Change selectedNumber to an object
scope.selectedNumber = { num : 1 };
- Change display to
<h2>{{ selectedNumber.num }}</h2>
- Change the click handler in
ng-repeat
tong-click="selectedNumber.num = number"
演示: Plunker
Demo: Plunker
解决方案2:
的使用 $父
范围内引用
的
Solution 2:
Use $parent
scope reference
- 更改
NG-重复
点击处理程序NG-点击=$ parent.selectedNumber =号
- Change the click handler in
ng-repeat
tong-click="$parent.selectedNumber = number"
演示: Plunker
解决方案3:
的父范围
的
- 创建像
$ scope.setSelectedNumber =功能(NUM)父范围setter方法{$ scope.selectedNumber = NUM}
- 单击事件更改为
setSelectedNumber(数字)
(这是已经使用的方法)
的更新:
的
如由Anders Ekdahl建议的,最好是使用基于对象(溶液1)溶液
Update:
As suggested by Anders Ekdahl, it is advisable to use the object (solution 1) based solution.
这篇关于为什么不分配在角前pressions总是工作?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!