来自使用转置的自定义指令的ng-controller的角度范围

时间:2016-08-17 10:21:53

标签: angularjs angularjs-ng-transclude

我仍然对Angular很新,所以如果这是一个愚蠢的问题,我道歉...我有一个使用翻译的自定义指令,我试图理解为什么数据绑定有效将ng-controller分配给父元素,但是当我直接将控制器分配给它时:

代码:

angular.module('HelloWorld', [])

.controller('HelloController', function($scope) {
  $scope.name = 'you'
})

.directive('hello', function() {
  return {
    restrict: 'E',
    transclude: true,
    template: '<ng-transclude />'
  };
});

HTML:

<!-- why does this one work? -->
<div ng-controller="HelloController">
  <hello>Hi there, {{name}}!</hello>
</div>

<!-- but not this one? -->
<hello ng-controller="HelloController">
  <p> Hi there, {{name}}!</p>
</hello>

Plunker:https://plnkr.co/edit/ICztHcKU4W2EgFmy8OqQ?p=preview

有什么想法吗?

1 个答案:

答案 0 :(得分:0)

指令被定义为一个函数,它返回一个被编译成元素的对象(带有模板,绑定,控制器和其他属性)。

无论你在元素中放置什么属性都传递给指令绑定(或隔离范围),它都不会被解释。

您可以在技术上将控制器作为属性传递给您的指令,但由于指令具有控制器属性,因此它看起来不是很好的做法。

例如,这可行:https://plnkr.co/edit/WknbSDI4HlQyp2vQIkbR?p=preview

angular.module('HelloWorld', [])

.controller('HelloController', function($scope) {
  $scope.name = 'you'
})

    .directive('hello', function() {
      return {
        restrict: 'E',
        scope: {
          ngController: '&'
        },
        transclude: true,
        template: '<ng-transclude />',
        controller: ngController
      };
    });

但是你看到你可以使用

controller: function() {}

直接在指令内部使其更加独立。