AngularJS:ng-if 不能与 ng-click 结合使用? [英] AngularJS: ng-if not working in combination with ng-click?

查看:36
本文介绍了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. 应该 1 吗?
  3. 为什么 2 有效?
  4. 应该 2 吗?
  5. 我可以依靠 2 在 AngularJS 的未来更新中工作吗?

推荐答案

  1. 为什么 1 不起作用?:因为 ngIf 定义了它自己的范围,该范围通常从其父范围继承(就像 ngRepeat 一样).因此,当您更改 ngIf 中某个字段的值时,您会在 ngIf 范围内更改它,而不是在其父范围内进行更改.
  2. 应该 1 吗?:
  3. 为什么 2 有效?:因为在这种情况下,您通过继承修改了 ngId 范围引用的对象的内容.
  4. 应该 2 行吗?:是的
  5. 我可以依靠 2 在 AngularJS 的未来更新中工作吗?:为什么不应该?
  1. 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.
  2. Should 1 work?: No
  3. Why does 2 work?: Because in that case you modify the content of an object which is referenced by the ngId scope, through inheritance.
  4. Should 2 work?: Yes
  5. Can I rely 2 to work in future updates of AngularJS?: Why shouldn't you?

这个范围继承机制在https://github.com/angular/angular中有很好的解释.js/wiki/理解范围

这篇关于AngularJS:ng-if 不能与 ng-click 结合使用?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆