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

1.1k views Asked by At

I've seen directives created like so:

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}}'
  };
});

The myCustomer directive is now on the Controller controller. If I define my module and controller and directive in different files like so:

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}}'
  };
});

How do I wire myCustomer into Controller to be able to display <my-customer> from in s

3

There are 3 answers

4
JB Nizet On BEST ANSWER

The myCustomer directive is now on the Controller controller

No, not at all. It has nothing to do with the controller. It just happens to expect a customer variable in the scope, and the controller happens to set such a variable in its scope. But you can use the directive whereever you want, in any view.

You use the controller and the directive the exact same way in your two examples. Whether they're defined in the same file or in different files doesn't change anything: as long as the files are both loaded by <script> tags of the html page, that will work the same way: the directive will display the customer of the controller scope if it's used inside a HTML element controller by the controller:

<div ng-controller="Controller"> 
    <my-customer></my-customer>
</div>
2
Debasish Mohapatra On

I think it depends on where you put the myCustomer directive, like suppose there is this div wired to Controller scope, and if you place your directive inside this div

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

then it will access your controller's (Controller) scope and print out the name and address

3
nalinc On

You may specify it in the 'controller' function of 'myCustomer' directive,

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

or

use ng-controller around the directive tags

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