如何将指令从模块添加到控制器?

How can I add a directive from a module to a controller?

我见过这样创建的指令:

angular.module('docsSimpleDirective', [])
.controller('Controller', ['$scope', function($scope) {
  $scope.customer = {
    name: 'Naomi',
    address: '1600 Amphitheatre'
  };
}])
.directive('myCustomer', function() {
  return {
    template: 'Name: {{customer.name}} Address: {{customer.address}}'
  };
});

myCustomer 指令现在在 Controller 控制器上。如果我像这样在不同的文件中定义我的模块和控制器和指令:

docsApp.js:

angular.module('docsSimpleDirective', []);

docsController.js:

angular.module('docsSimpleDirective')
.controller('Controller', ['$scope', function($scope) {
  $scope.customer = {
    name: 'Naomi',
    address: '1600 Amphitheatre'
  };
}])

docsSimpleDirective.js:

angular.module('docsSimpleDirective')
.directive('myCustomer', function() {
  return {
    template: 'Name: {{customer.name}} Address: {{customer.address}}'
  };
});

如何将 myCustomer 连接到 Controller 以便能够显示来自 s

<my-customer>

我认为这取决于您放置 myCustomer 指令的位置,例如假设 有这个 div 连接到控制器范围,如果你把你的指令放在这个 div

<div ng-controller = "Controller" > 
     <my-customer></my-customer>
</div>

然后它将访问你的控制器(Controller)范围并打印出名称和地址

The myCustomer directive is now on the Controller controller

不,一点也不。它与控制器无关。它恰好在范围内期望一个客户变量,而控制器恰好在其范围内设置了这样一个变量。但是您可以在任何视图中的任何地方使用该指令。

您在两个示例中以完全相同的方式使用控制器和指令。无论它们是在同一个文件中还是在不同的文件中定义都不会改变任何东西:只要文件都由 html 页面的 <script> 标签加载,那将以相同的方式工作:如果控制器在 HTML 元素控制器中使用该指令,则该指令将显示控制器范围的客户:

<div ng-controller="Controller"> 
    <my-customer></my-customer>
</div>

您可以在'myCustomer'指令的'controller'函数中指定它,

angular.module('docsSimpleDirective')
.directive('myCustomer', function() {
  return {
    restrict:'E',
    controller:'Controller',
    template: 'Name: {{customer.name}} Address: {{customer.address}}'
  };
});

在指令标签周围使用 ng-controller

<div ng-controller = "Controller" > 
     <my-customer></my-customer>
</div>