Inheritance for scopes in AngularJS

前端 未结 2 1302
遇见更好的自我
遇见更好的自我 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: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'
      };
    }
    

提交回复
热议问题