继承于AngularJS范围 [英] Inheritance for scopes in AngularJS
问题描述
在父母控制范围,我已经定义了将selectedItem
被设定为X。然后在子范围,我已经定义了将selectedItem
使用ngModel:
In a parent controller scope, I have defined selectedItem
which is set to 'x'. Then in the child scope, I have defined selectedItem
using ngModel:
<div ng-app>
<div ng-controller="CtrlA">
<div ng-controller="CtrlB">
<select ng-model="selectedItem" ng-options="item for item in items">
</select>
</div>
</div>
</div>
function CtrlA($scope) {
$scope.selectedItem = 'x';
$scope.items = ['x', 'y'];
}
function CtrlB($scope) {}
在页面加载时,将selectedItem
正确预期设定为X。当我选择'Y',将selectedItem
在CTRLB $范围给出了Y预期。
When the page is loaded, the selectedItem
is properly set to 'x' as expected. When I select 'y', selectedItem
in CtrlB $scope gives 'y' as expected.
但是,当我检查 $ scope.selectedItem
在 CTRLA
范围(使用AngularJS的batarang),它给'X
But when I inspect $scope.selectedItem
in CtrlA
scope (using AngularJS's batarang), it gives 'x' .
的jsfiddle: http://jsfiddle.net/sudhh/GGKjp/2/
jsFiddle: http://jsfiddle.net/sudhh/GGKjp/2/
preVIEW页: http://fiddle.jshell.net / sudhh / GGKjp / 2 /显示/光/ (与angularjs batarang检查)
Preview page: http://fiddle.jshell.net/sudhh/GGKjp/2/show/light/ (for inspecting with angularjs batarang)
为什么 $ scope.selectedItem
在 CTRLA
范围不会得到更新为'Y'?是什么原因呢?
Why is $scope.selectedItem
in CtrlA
scope not getting updated to 'y'? What is the explanation?
我preFER不使用父范围的事件或 rootScope
更新将selectedItem
(用于学习目的)。
I prefer not to use events or rootScope
to update selectedItem
in parent scope (for learning purposes).
推荐答案
如果您尝试绑定到一个原始的父范围中声明,然后在子作用域则selectedItem将有效遮盖同名的财产在父范围。
If you try to bind to a primitive declared on parent scope, then the selectedItem in child scope will effectively shadow the property of the same name in the parent scope.
在此情况下,有3种选择
In this case there are 3 choices
- 定义的父对象为你的模型,然后引用
在孩子该对象的属性:ref.selectedItem - 使用$ parent.selectedItem(并不总是可能的,但更容易比1。
在可能的情况) - 上定义的父范围的功能,并且从子调用它,
传递原始值到父(并不总是可能)
更多关于它的<一个href=\"https://github.com/angular/angular.js/wiki/The-Nuances-of-Scope-Prototypal-Inheritance\">https://github.com/angular/angular.js/wiki/The-Nuances-of-Scope-Prototypal-Inheritance
您可以在 http://jsfiddle.net/sudhh/XU2rP/1/ <发现使用第一种方式更新的小提琴/ A>
You can find the updated fiddle using the first approach at http://jsfiddle.net/sudhh/XU2rP/1/
function CtrlA($scope) {
$scope.items = ['x', 'y'];
$scope.ref = {
selectedItem: 'x'
};
}
这篇关于继承于AngularJS范围的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!