AngularJS:ng-if 不能与 ng-click 结合使用?
问题描述:
鉴于此使用 AngularJS 1.2 rc3 的测试用例:http://plnkr.co/edit/MX6otx(下面重复)
Given this test case using AngularJS 1.2 rc3: http://plnkr.co/edit/MX6otx (repeated below)
1.
<li ng-init="toggle1 = false">
ng-if toggle1: {{ toggle1 }}
<p>
<button ng-if="!toggle1" ng-click="toggle1 = true">Turn On</button>
<button ng-if="toggle1" ng-click="toggle1 = false">Turn Off</button>
does not work
</li>
2.
<li ng-init="obj={toggle2:false}">
ng-if obj.toggle2: {{ obj.toggle2 }}
<p>
<button ng-if="!obj.toggle2" ng-click="obj.toggle2 = true">Turn On</button>
<button ng-if="obj.toggle2" ng-click="obj.toggle2 = false">Turn Off</button>
then why does this work?
</li>
问题:
- 为什么 1 不起作用?
- 应该 1 吗?
- 为什么 2 有效?
- 应该 2 吗?
- 我可以依靠 2 在 AngularJS 的未来更新中工作吗?
答
- 为什么 1 不起作用?:因为 ngIf 定义了它自己的范围,该范围通常从其父范围继承(就像 ngRepeat 一样).因此,当您更改 ngIf 中某个字段的值时,您会在 ngIf 范围内更改它,而不是在其父范围内进行更改.
- 应该 1 吗?: 否
- 为什么 2 有效?:因为在这种情况下,您通过继承修改了 ngId 范围引用的对象的内容.
- 应该 2 行吗?:是的
- 我可以依靠 2 在 AngularJS 的未来更新中工作吗?:为什么不应该?
- Why does 1 not work?: Because an ngIf defines its own scope, which prototypically inherits from its parent scope (just like ngRepeat). So, when you change the value of a field inside an ngIf, you change it in the ngIf scope, and not in its parent scope.
- Should 1 work?: No
- Why does 2 work?: Because in that case you modify the content of an object which is referenced by the ngId scope, through inheritance.
- Should 2 work?: Yes
- Can I rely 2 to work in future updates of AngularJS?: Why shouldn't you?
这个范围继承机制在https://github.com/angular/angular中有很好的解释.js/wiki/理解范围