Search code examples
javascriptangularjsangular-ng-if

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


I'm finding this issue strange.

Basically I want a block to exist on a page based on an ng-if condition. But when I try to modify that ng-if inside said block, it doesn't have any effect on any other elements.

Why is this happening?

The JSFiddle is here and the code is below:

<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>

Solution

  • This is an issue with ng-if child scope and the fact you are trying to 2-way bind a primitive in a child scope.

    You should always try to use objects in your scope as models so that you leverage the benefits of prototypical inheritance.

    See the difference here:

    <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}
    }
    

    Also read the docs for ng-init. It should not be used for arbitrary variables. It's main purpose is for aliasing variables in ng-repeat

    DEMO