传递给子指令时,父指令控制器未定义

时间:2017-03-23 20:58:39

标签: angularjs angularjs-directive

我在this post询问了一般问题。我用工作的例子得到了答案;但是,当我尝试使用此示例来修改现有代码时,我收到错误。 请参阅下面的代码和Plunker page

HTML

<script src="https://cdnjs.cloudflare.com/ajax/libs/angular.js/1.5.3/angular.min.js"></script>
<div ng-app="myApp">
  <tmp-menu ng-disabled="true">
    <tmp-menu-link></tmp-menu-link>
    <tmp-menu-link></tmp-menu-link>
  </tmp-menu>
</div>

的JavaScript(AngularJS):

angular.module('myApp', [])
.controller('MyDirectiveController', MyDirectiveController)
.directive('tmpMenu', function() {
  return {
    restrict: 'AE',
    replace:true,
    transclude:true,
    scope:{
      disabled: '=?ngDisabled'
    },
    controller: 'MyDirectiveController',
    template: '<div>myDirective Disabled: {{ disabled }}<ng-transclude></ng-transclude></div>',
    link: function(scope, element, attrs) {


    }
  };
})
.directive('tmpMenuLink', function() {
  return {
    restrict: 'AE',
    replace:true,
    transclude:true,
    scope:{
    },
    required:'^^tmpMenu',
    template: '<div>childDirective disabled: {{ disabled }}</div>',
    link: function(scope, element, attrs, MyDirectiveCtrl) {
      console.log(MyDirectiveCtrl);

      scope.disabled = MyDirectiveCtrl.isDisabled();

    }
  };
})

function MyDirectiveController($scope) {
  this.isDisabled = function() {
    return $scope.disabled;
  };
}

内部指令 tmpMenuLink MyDirectiveCtrl 未定义。 那是为什么?

2 个答案:

答案 0 :(得分:1)

因为require不是required

&#13;
&#13;
angular.module('myApp', [])
  .controller('MyDirectiveController', MyDirectiveController)
  .directive('tmpMenu', function() {
    return {
      restrict: 'AE',
      replace: true,
      transclude: true,
      scope: {
        disabled: '=?ngDisabled'
      },
      controller: 'MyDirectiveController',
      template: '<div>myDirective Disabled: {{ disabled }}<ng-transclude></ng-transclude></div>',
      link: function(scope, element, attrs) {}
    };
  })
  .directive('tmpMenuLink', function() {
    return {
      restrict: 'AE',
      replace: true,
      transclude: true,
      require: '^^tmpMenu',
      template: '<div>childDirective disabled: {{ disabled }}</div>',
      link: function(scope, element, attrs, MyDirectiveController) {

        scope.disabled = MyDirectiveController.isDisabled();

      }
    };
  })

function MyDirectiveController($scope) {
  this.isDisabled = function() {
    return $scope.disabled;
  };
}
&#13;
<script src="https://cdnjs.cloudflare.com/ajax/libs/angular.js/1.5.3/angular.min.js"></script>
<div ng-app="myApp">
  <tmp-menu ng-disabled="true">
    <tmp-menu-link></tmp-menu-link>
    <tmp-menu-link></tmp-menu-link>
  </tmp-menu>
</div>
&#13;
&#13;
&#13;

答案 1 :(得分:1)

您的代码中有拼写错误:

required:'^^tmpMenu',

将其更改为

require:'^^tmpMenu',

检查此plunkr

https://plnkr.co/edit/DgyW3OFgr1GyAR8fuATi?p=preview