admin管理员组文章数量:1180476
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=".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'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>
http://jsfiddle.net/78R52/
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
.
3 Answers
Reset to default 26ng-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/
Ah, ng-if
creates a new scope! So, "there has to be a dot in the model name"!
http://jsfiddle.net/78R52/2/
As others have said, ng-if has its own scope. What i want to say, it's a bad practice to put expressions in the view. The good practice is to have a scope function that's called within the view.
var ctrl = function($scope){
$scope.foo = false;
$scope.fn = fn;
function fn(){
$scope.foo = true;
}
/////
<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="fn()">Show foo</button>
</div>
<button ng-click="fn()">Show foo</button>
</div>
本文标签: javascriptModel does not update within ngifStack Overflow
版权声明:本文标题:javascript - Model does not update within ng-if - Stack Overflow 内容由网友自发贡献,该文观点仅代表作者本人, 转载请联系作者并注明出处:http://www.betaflare.com/web/1738181249a2067487.html, 本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌抄袭侵权/违法违规的内容,一经查实,本站将立刻删除。
发表评论