这是小提琴展示的问题。http://jsfiddle.net/Erk4V/1/
如果我在ng-if中有一个ng-模型,那么模型就不能像预期的那样工作。
我想知道这是一个错误,还是我误解了正确的用法。
<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>
ng-if指令和其他指令一样创建子作用域。请参阅下面的脚本(或此jsfiddle)
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.0rc1/angular.min.js"></script>
<script>
function main($scope) {
$scope.testa = false;
$scope.testb = false;
$scope.testc = false;
$scope.obj = {test: false};
}
</script>
<div ng-app >
<div ng-controller="main">
Test A: {{testa}}<br />
Test B: {{testb}}<br />
Test C: {{testc}}<br />
{{obj.test}}
<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" /> {{testb}}
</div>
<div ng-if="!someothervar">
testc (with ng-if): <input type="checkbox" ng-model="testc" />
</div>
<div ng-if="!someothervar">
object (with ng-if): <input type="checkbox" ng-model="obj.test" />
</div>
</div>
</div>
因此,您的复选框更改了子作用域内部的testb,但没有更改外部的父作用域。
注意,如果想要修改父范围内的数据,就需要修改对象的内部属性,就像我添加的最后一个div中那样。