Inheritance for scopes in AngularJS

前端 未结 2 1296
遇见更好的自我
遇见更好的自我 2021-01-03 00:59

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

相关标签:
2条回答
  • 2021-01-03 01:44

    I've noticed in similar cases that AngularJS does not watch selectedItem properly. The only way I found is to initialize selectedItem with an entry from the items array. Try the following:

    function CtrlA($scope) {
        $scope.items = ['x', 'y'];
        $scope.selectedItem = $scope.items[0];
    }
    
    0 讨论(0)
  • 2021-01-03 01:51

    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.

    In this case there are 3 choices

    1. define objects in the parent for your model, then reference a property of that object in the child: ref.selectedItem
    2. use $parent.selectedItem (not always possible, but easier than 1. where possible)
    3. define a function on the parent scope, and call it from the child, passing the primitive value up to the parent (not always possible)

    More about it on https://github.com/angular/angular.js/wiki/The-Nuances-of-Scope-Prototypal-Inheritance

    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'
      };
    }
    
    0 讨论(0)
提交回复
热议问题