AngularJS ng-model在ng-if里面无效

参考stackflow原文。app

问题:ide

Here is the fiddle showing the problem. http://jsfiddle.net/Erk4V/1/this

It appears if I have an ng-model inside of an ng-if, the model does not work as expected..net

I am wondering if this is a bug or if I am misunderstanding the proper usage.code

<div ng-app >
    <div ng-controller="main">

        Test A: {{testa}}<br />
        Test B: {{testb}}<br />
        Test C: {{testc}}<br />

        <div>
            testa (without ng-if): <input type="checkbox" ng-model="testa" />
        </div>
        <div ng-if="!testa">
            testb (with ng-if): <input type="checkbox" ng-model="testb" />
        </div>
        <div ng-if="!someothervar">
            testc (with ng-if): <input type="checkbox" ng-model="testc" />
        </div>

    </div>
</div>

回答:

The ng-if directive, like other directives creates a child scope. See this fiddle:http://jsfiddle.net/Erk4V/4/对象

So, your checkbox changes the testb inside of the child scope, but not the outer parent scope.get

Note, that if you want to modify the data in the parent scope, you'll need to modify the internal properties of an object like in the last div that I added.input

 

 

我的解释:ng-if里面会生成一个子域,想要ng-model生效,须要在$scope建立一个子对象,才行,如$scope.obj,再将ng-model绑定到objit

使用ng-show(或ng-hide)能够间接解决这个问题。ast

相关文章
相关标签/搜索