小编典典

AngularJS中范围的继承

angularjs

在父控制器作用域中,我已定义将selectedItem其设置为“ x”。然后在子范围中,我selectedItem使用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中$
scope会按预期给出“ y”。

但是,当我检查$scope.selectedItemCtrlA范围(使用AngularJS的batarang),它给“X”。

jsFiddle:http :
//jsfiddle.net/sudhh/GGKjp/2/

预览页面:http :
//fiddle.jshell.net/sudhh/GGKjp/2/show/light/(用于与angularjs batarang一起检查)

为什么$scope.selectedItemCtrlA范围内没有得到更新,以“Y”?有什么解释?

我不希望使用事件或在父范围内rootScope进行更新selectedItem(出于学习目的)。


阅读 367

收藏
2020-07-04

共1个答案

小编典典

如果尝试绑定到在父作用域上声明的基元,则子作用域中的selectedItem将有效地遮盖父作用域中同名的属性。

在这种情况下,有3个选择

  1. 在模型的父级中定义对象,然后在子级中引用该对象的属性:ref.selectedItem
  2. 使用$ parent.selectedItem(并非总是可能,但比1.容易)
  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'
  };
}
2020-07-04