这是显示问题的小提琴.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>
Run Code Online (Sandbox Code Playgroud)
Jon*_*on7 218
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>
Run Code Online (Sandbox Code Playgroud)
因此,您的复选框会更改testb
子范围内部,但不会更改外部父范围.
请注意,如果要修改父作用域中的数据,则需要修改对象的内部属性,就像我添加的最后一个div一样.
zs2*_*020 203
您可以使用它$parent
来引用父作用域中定义的模型
<input type="checkbox" ng-model="$parent.testb" />
Run Code Online (Sandbox Code Playgroud)
Vas*_*tin 47
您可以使用ngHide (或ngShow)指令.它不像ngIf那样创建子范围.
<div ng-hide="testa">
Run Code Online (Sandbox Code Playgroud)
小智 7
在许多其他情况下我们有这个,我们内部决定总是有一个控制器/指令的包装器,这样我们就不需要考虑它了.这是你的包装器的例子.
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.0rc1/angular.min.js"></script>
<script>
function main($scope) {
$scope.thisScope = $scope;
$scope.testa = false;
$scope.testb = false;
$scope.testc = false;
$scope.testd = false;
}
</script>
<div ng-app >
<div ng-controller="main">
Test A: {{testa}}<br />
Test B: {{testb}}<br />
Test C: {{testc}}<br />
Test D: {{testd}}<br />
<div>
testa (without ng-if): <input type="checkbox" ng-model="thisScope.testa" />
</div>
<div ng-if="!testa">
testb (with ng-if): <input type="checkbox" ng-model="thisScope.testb" />
</div>
<div ng-show="!testa">
testc (with ng-show): <input type="checkbox" ng-model="thisScope.testc" />
</div>
<div ng-hide="testa">
testd (with ng-hide): <input type="checkbox" ng-model="thisScope.testd" />
</div>
</div>
</div>
Run Code Online (Sandbox Code Playgroud)
Yishay,希望这会有所帮助
归档时间: |
|
查看次数: |
101803 次 |
最近记录: |