AngularJS ng-if 和作用域 [英] AngularJS ng-if and scopes
问题描述
我正在尝试理解 ng-if 和作用域.据我所知,ng-if 创建了一个新的子作用域.这是我的问题:
查看
<div ng-if="!someCondition"><input ng-model="$parent.someValue2"/>
控制器
$scope.someCondition = true;如果($scope.someCondition){$scope.someValue2 = $scope.someValue1;}
如果 someCondition 设置为 true,那么 someValue2 应该与 someValue1 相同.
我的问题是在两种情况下(真或假)我都无法访问 someValue2.我怎么能做到这一点?
是的,ng-if
创建一个新的子作用域
要在 ng-if
中查看模型属性,经验法则是:
请勿将范围用作模型
例如
ng-if='showStuff'//这里我的范围是模型 **INCORRECT**ng-if='someObject.showStuff'//** 正确 **
在 ng-model 中使用对象属性 - 那么,即使 ng-if
创建新的子作用域,父作用域也会发生变化.
要查看工作的 Plunker,请看这里:http://jsfiddle.net/Erk4V/4/一个>
I am trying to understand ng-if and scopes. As I am aware, ng-if creates a new child scope. Here is my issue:
View
<input ng-model="someValue1" />
<div ng-if="!someCondition">
<input ng-model="$parent.someValue2" />
</div>
Controller
$scope.someCondition = true;
if ($scope.someCondition) {
$scope.someValue2 = $scope.someValue1;
}
If someCondition is set to true, then someValue2 should be the same as someValue1.
My problem is that I can't access someValue2 in both situations (true or false). How could I achieve this?
Yes, ng-if
creates a new child scope
To watch a model property in an ng-if
, the rule-of-thumb is:
DO NOT USE THE SCOPE AS MODEL
e.g.
ng-if='showStuff' //here my scope is model **INCORRECT**
ng-if='someObject.showStuff' // ** CORRECT **
Use an object property in ng-model - then, even if ng-if
creates the new child scope, the parent scope will have the changes.
To see a working Plunker, look here : http://jsfiddle.net/Erk4V/4/
这篇关于AngularJS ng-if 和作用域的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!