模型不会在 ng-if 内更新 [英] Model does not update within ng-if
本文介绍了模型不会在 ng-if 内更新的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我在 Angular 应用程序中有一个奇怪的行为,我不知道这是错误还是已知限制:
'use strict';var ctrl = 函数($scope){$scope.foo = false;};
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script><div ng-app ng-controller="ctrl">富:{{富}}<div ng-if="foo" style="background-color: #f00;"><p>foo</p>
<div ng-if="!foo"><br/><button ng-click="foo = true;">显示 foo</button>
<button ng-click="foo = true">显示 foo</button>
我希望单击其中一个按钮会设置 foo = true
,但单击第一个按钮(在 ng-if="!foo"
内)不会不改变模型.
测试版本为1.2.1
.
解决方案
ng-if
有自己的作用域,所以需要使用:
<br/><button ng-click="$parent.foo = true;">显示 foo</button>
更新小提琴:http://jsfiddle.net/78R52/1/
I've got a strange behavior in an angular application and I don't know if that's a bug or a known limitation:
'use strict';
var ctrl = function ($scope) {
$scope.foo = false;
};
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>
<div ng-app ng-controller="ctrl">
foo: {{foo}}
<div ng-if="foo" style="background-color: #f00;">
<p>foo</p>
</div>
<div ng-if="!foo">
<br/><button ng-click="foo = true;">Show foo</button>
</div>
<button ng-click="foo = true">Show foo</button>
</div>
I would expect that clicking one of the buttons would set foo = true
, but clicking the first button (within the ng-if="!foo"
) doesn't change the model.
Tested version is 1.2.1
.
解决方案
ng-if
has its own scope, so you need to use:
<br/><button ng-click="$parent.foo = true;">Show foo</button>
Updated fiddle: http://jsfiddle.net/78R52/1/
这篇关于模型不会在 ng-if 内更新的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!