且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

为什么在angularjs中找不到所需指令的控制器?

更新时间:2023-02-12 15:40:50

AFAIK,子指令中不能包含控制器.

AFAIK, you cannot have a controller in the child directive.

演示: http://plnkr.co/edit/kv9udk4eB5B2y8SBLGQd?p=preview

app.directive('foo', [
   '$log', function($log) {
     return {
      restrict: 'E',
      replace: true,
      transclude: true,
      template: '<div id="test" ng-transclude></div>',
      controller: function($scope) {
        $scope.panes = ['Item1','Item2','Item3'] 
        return { 
          getPanes: function() { return $scope.panes; }
        };
      },
      link: function(scope, element, attrs, ctrl) {
        $log.log('test1', ctrl, ctrl.getPanes(), scope.panes);  
      }
    };
  }
]);

我删除了子控制器.

app.directive('bar', [
  '$log', function($log) {
    return {
      restrict: 'E',
      replace: true,
      transclude: true,
      require: '^?foo',
      template: '<div ng-transclude></div>',
      link: function(scope, element, attrs, ctrl) {
        scope.x = 1;
        $log.log('test2', ctrl, ctrl.getPanes(), scope.panes, scope.x);
      }
    };
  }
]);