能否在使用它的块内修改 ng-if 变量?

Can ng-if variable be modified inside a block that is using it?

我觉得这个问题很奇怪。

基本上我希望基于 ng-if 条件的页面上存在一个块。但是当我尝试修改所述块内的 ng-if 时,它对任何其他元素没有任何影响。

为什么会这样?

The JSFiddle is here 代码如下:

<div ng-controller="MyCtrl">
    <div ng-init="shouldShow=false">
        <div ng-if="!shouldShow">
            <p>{{shouldShow}}</p>
            <div>
                <button ng-click="shouldShow=!shouldShow">Hide Section</button>
                <button ng-if="!shouldShow">Should Disappear</button>
            </div>
        </div>
    </div>
</div>

这是 ng-if 子作用域的问题,事实上您正在尝试在子作用域中双向绑定原语。

您应该始终尝试在您的范围内使用对象 models 以便您利用原型继承的好处。

看这里的区别:

<div ng-controller="Ctrl">
      <div >
        <p>{{model.shouldShow}}</p>
        <div ng-if="!model.shouldShow">
            <button ng-click="model.shouldShow=!model.shouldShow">Hide Section</button>
            <p>{{model.shouldShow}}</p>
        </div>
    </div>
</div>

JS

function Ctrl($scope) {
    $scope.model={shouldShow:false}
}

另请阅读 ng-init 的文档。它不应该用于任意变量。它的主要目的是为 ng-repeat

中的变量别名

DEMO

documentation of ng-if 解释了会发生什么:

Note that when an element is removed using ngIf its scope is destroyed and a new scope is created when the element is restored. The scope created within ngIf inherits from its parent scope using prototypal inheritance. An important implication of this is if ngModel is used within ngIf to bind to a javascript primitive defined in the parent scope. In this case any modifications made to the variable within the child scope will override (hide) the value in the parent scope.

简而言之:一旦您在子作用域中修改了 shouldShow,它就会覆盖父作用域的 shouldShow(原型继承)。正如在另一个答案中指出的那样,这可以通过共享对象间接解决:wrapperObject.shouldShow。除非您在子作用域中为 wrapperObject 分配新值,否则它将指向与父作用域相同的实例(因此包含 shouldShow 的相同实例)。