在父控制器作用域中,我定义了selectedItem,它被设置为'x‘。然后在子作用域中,我使用ngModel定义了selectedItem:
<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‘时,CtrlB $scope中的selectedItem给出了预期的'y’。
但是当我在CtrlA作用域中检查$scope.selectedItem时(使用AngularJS的batarang),它给出了'x‘。
jsFiddle:http://jsfiddle.net/sudhh/GGKjp/2/
预览页面:http://fiddle.jshell.net/sudhh/GGKjp/2/show/light/ (用于使用angularjs batarang进行检查)
为什么CtrlA作用域中的$scope.selectedItem没有更新为'y'?解释是什么?
我不喜欢使用events或rootScope来更新父作用域中的selectedItem (出于学习目的)。
发布于 2013-01-09 19:37:35
如果您尝试绑定到父作用域中声明的原语,那么子作用域中的selectedItem将有效地隐藏父作用域中同名的属性。
在这种情况下,有3种选择
有关它的更多信息,请访问https://github.com/angular/angular.js/wiki/The-Nuances-of-Scope-Prototypal-Inheritance
您可以使用第一种方法在http://jsfiddle.net/sudhh/XU2rP/1/找到更新后的小提琴
function CtrlA($scope) {
$scope.items = ['x', 'y'];
$scope.ref = {
selectedItem: 'x'
};
}发布于 2013-01-09 18:01:31
我注意到在类似的情况下,AngularJS不能正确地观看selectedItem。我找到的唯一方法是使用items数组中的条目初始化selectedItem。尝试以下操作:
function CtrlA($scope) {
$scope.items = ['x', 'y'];
$scope.selectedItem = $scope.items[0];
}https://stackoverflow.com/questions/14232397
复制相似问题