Angular:父指令不受其子项更改的影响

时间:2015-11-16 18:45:45

标签: javascript angularjs angularjs-scope directive

我有一个categoryList指令,可以生成一个选择的类别框。该指令工作正常,当我选择一个类别时,ngModel中提到的外部控制器作用域属性会正确更新。但是,当我将categoryList放入另一个指令(subCategoryList)时,subCategoryList的范围未正确更新。

您可以在此代码段中看到此问题行为:在第一个选择框中,您可以看到任何更改都将在外部范围内更新,但在第二个选择框中,更改会被"卡住&#34 ;在categoryList指令中,并且不会影响subCategoryList



angular.module('plunker', [])

  .controller('MainCtrl', function($scope) {
    
  }).directive('categoryList', function () {
  return {
    restrict: 'E',
    template: 'categoryList debug: {{model}}<br/><br/><select ng-options="cat as cat.name for cat in categories track by cat.id" ng-model="model" class="form-control"><option value="">{{emptyOptLabel}}</option></select>',
    scope: {
      model: '=ngModel',
      categories: '=?',
      catIdField: '@',
      emptyOptLabel:'@'
    },
    link: categoryListLink
  };

  function categoryListLink(scope, el, attrs) {
    if (angular.isUndefined(scope.catIdField)) {
      scope.catIdField = 'categoryId';
    }

    if(angular.isUndefined(scope.emptyOptLabel)){
      scope.emptyOptLabel = 'category';
    }

    if( !scope.categories ) {
      scope.categories = [
        {
          'categoryId':123,
          'name':'cat1',
          'subCategories':[
            {
              'subCategoryId':123,
              'name':'subcat1'
            }
          ]
        }
        ];
    }
    prepareCats(scope.categories);

    function prepareCats(cats){
      cats.forEach(function (cat) {
        cat.id = cat[scope.catIdField];
      });
      return cats;
    }
  }
}).directive('subCategoryList', function () {
  return {
    restrict: 'E',
    template: 'subCategoryList debug:{{model}}<br/><br/><category-list ng-if="parent && parent.subCategories.length !== 0" ng-model="model" categories="parent.subCategories" cat-id-field="subCategoryId" empty-opt-label="sub category"></category-list>',
    scope: {
      model: '=ngModel',
      parent: '='
    }
  };
});
&#13;
<!DOCTYPE html>
<html ng-app="plunker">

  <head>
    <meta charset="utf-8" />
    <title>AngularJS Plunker</title>
    <script data-require="angular.js@1.*" data-semver="1.4.3" src="https://code.angularjs.org/1.4.3/angular.js"></script>
    <script src="app.js"></script>
  </head>

  <body ng-controller="MainCtrl as main">
    Outer debug: {{main.cat}}<br/><br/>
    <category-list ng-model="main.cat" empty-opt-label="category"></category-list><br/><br/>
    <sub-category-list ng-model="main.subcat" parent="main.cat"></sub-category-list>
  </body>

</html>
&#13;
&#13;
&#13; 有人知道这里可能出现什么问题?

1 个答案:

答案 0 :(得分:2)

这是与指令ng-if中的subCategoryList相关的范围问题。如果删除它,代码就会开始工作。