AngularJS:NG-如果不结合NG单击工作吗? [英] AngularJS: ng-if not working in combination with ng-click?
本文介绍了AngularJS:NG-如果不结合NG单击工作吗?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
: http://plnkr.co/edit/MX6otx (下面重复)
1
<李NG-的init =toggle1 =假>
NG-如果toggle1:{{toggle1}}
&所述p为H.;
<按钮NG-IF =!toggle1NG点击=toggle1 =真正的>打开针对< /按钮>
<按钮NG-IF =toggle1NG点击=toggle1 =假>关闭< /按钮>
不工作
< /李>
2
<李NG-的init =OBJ = {toggle2:假}>
NG-如果obj.toggle2:{{obj.toggle2}}
&所述p为H.;
<!obj.toggle2按钮NG-IF = NG点击=obj.toggle2 =真正的>打开针对< /按钮>
<按钮NG-IF =obj.toggle2NG点击=obj.toggle2 =假>关闭< /按钮>
那么为什么这项工作?
< /李>
问题:
- 为什么1不工作?
- 应在1工作?
- 为什么2工作?
- 应在2工作?
- 我可以依靠2到AngularJS的未来的更新工作?
解决方案
- 为什么1不起作用:,因为ngIf定义了自己的范围,该范围中典型从其父范围(就像ngRepeat)继承。所以,当你改变ngIf内字段的值,你改变它在ngIf范围内,而不是在它的父范围。
- 应在1工作:否
- 为什么2工作:因为在这种情况下,修改这是由ngId范围引用的对象,的的内容的通过继承
- 应在2工作:是
- 我可以依靠2 AngularJS的未来的更新工作:??为什么你不应该
此范围内的继承机制在<一个很好的解释href=\"https://github.com/angular/angular.js/wiki/Understanding-Scopes\">https://github.com/angular/angular.js/wiki/Understanding-Scopes
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>
Questions:
- Why does 1 not work?
- Should 1 work?
- Why does 2 work?
- Should 2 work?
- Can I rely 2 to work in future updates of 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?
This scope inheritance mechanism is explained very well in https://github.com/angular/angular.js/wiki/Understanding-Scopes
这篇关于AngularJS:NG-如果不结合NG单击工作吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文