javascript 模型不会在 ng-if 内更新
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/20067467/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Model does not update within ng-if
提问by stofl
I've got a strange behavior in an angular application and I don't know if that's a bug or a known limitation:
我在 angular 应用程序中有一个奇怪的行为,我不知道这是错误还是已知限制:
'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.
我希望单击其中一个按钮会设置foo = true
,但单击第一个按钮(在 内ng-if="!foo"
)不会更改模型。
Tested version is 1.2.1
.
测试版本是1.2.1
.
回答by thebenedict
ng-if
has its own scope, so you need to use:
ng-if
有它自己的范围,所以你需要使用:
<br/><button ng-click="$parent.foo = true;">Show foo</button>
Updated fiddle: http://jsfiddle.net/78R52/1/
更新小提琴:http: //jsfiddle.net/78R52/1/
回答by stofl
Ah, ng-if
creates a new scope! So, "there has to be a dot in the model name"!
啊,ng-if
创建一个新的范围!所以,“型号名称中必须有一个点”!
回答by Mahmood .K Samaha
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.
正如其他人所说,ng-if 有自己的范围。我想说的是,将表达式放在视图中是一种不好的做法。好的做法是拥有一个在视图中调用的作用域函数。
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>