Angular: 父指令不受其子指令变化的影响

Angular: parent directive isn't affected by changes in its child

我有一个 categoryList 指令,它生成一个 select 类别框。该指令工作正常,当我 select 一个类别时,ngModel 中提到的范围为 属性 的外部控制器会正确更新。但是当我把 categoryList 放在另一个指令 (subCategoryList) 中时,subCategoryList 的范围没有正确更新。

您可以在此代码段中看到这个有问题的行为:在第一个 select 框中,您可以看到任何更改都将在外部范围中更新,但在第二个 select 框中, categoryList 指令中的 "stuck" 更改,不影响 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: '='
    }
  };
});
<!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>
有人知道这里可能是什么问题吗?

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