2

我在 angularjs 中写了两个指令,一个嵌入在另一个中。

以下是指令的脚本:

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

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

下面是一段html:

<foo ng-controller="IndexController">
      <bar></bar>
    </foo>

下面是生成的元素,从 chrome 开发者工具中检查

<div id="test" ng-transclude="" ng-controller="IndexController" class="ng-scope">
      <div ng-transclude="" class="ng-scope"></div>
    </div>

下面是 chrome 控制台输出:

test2 
Array[0]
length: 0
__proto__: Array[0]
 angular.js:5930
test1 
Array[0]
length: 0
__proto__: Array[0]  

问题: 子指令无法获取父指令的控制器,所以“bar”链接函数的第四个参数“fooCtrl”是一个空数组。我做错了什么?

更新和回答:

最后我找到了导致奇怪结果的原因。这只是我犯的一个愚蠢的错误:

 // in directive "foo"
 controller: function($scope) {
    this.scope = $scope;
    // This line below is wrong. It is here 
    // because I transcompiled coffeescript to js.
    // return $scope.panes = [];
    // It should be like below:
    $scope.panes = []
    // I should have written .coffee like below
    // controller: ($scope) ->
    //     @scope = $scope
    //     $scope.panes = []
    //     return # prevent coffeescript returning the above expressions.
    //     # I should rather have added the above line
  }

纠正错误后,我尝试并发现没有什么可以阻止使用控制器或在子指令中提供空内容。

4

1 回答 1

2

AFAIK,您不能在子指令中拥有控制器。

演示: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);
      }
    };
  }
]);
于 2013-10-09T03:12:11.297 回答