1

I'm switching from a directive created using:

return {
    restrict: 'E',
    templateUrl: '/src/templates/noise/swatches.html',
    link: link,
    controller: "swatchesController"
};

and

<swatches-directive></swatches-directive>

to using:

return {
    restrict: 'E',
    templateUrl: '/src/templates/noise/swatches.html',
    link: link,
    require: "ngController"
};

and

<swatches-directive ng-controller="swatchesController"></swatches-directive>

This seems to have unanticipated side-effects on existing watches belonging to other directives against scope variables that the swatches-directive assigns to. From what I understand, the new way introduces a new scope, so assigning watched variables to the parent scope seems like it should work, but those watches refuse to trigger.

Are there fundamental differences between the two methods used above?

deworde
  • 2,679
  • 5
  • 32
  • 60
  • Check this http://stackoverflow.com/questions/15672709/how-to-require-a-controller-in-an-angularjs-directive – Nitin Varpe Jun 23 '15 at 10:33
  • Where are the watches assigned? And where do they fail to trigger? – Davin Tryon Jun 23 '15 at 10:39
  • @DavinTryon The watches are assigned on another directive, which is a sibling of swatches-directive. They fail to trigger when swatchesController updates one of their properties. I'll try and create a simplest possible example. – deworde Jun 23 '15 at 10:55

2 Answers2

0

Few points to note:

  1. You should use the controllerAs property to segregate the controllers. It's considered as a best practice. You can read it here
  2. Ideally, you should provide the controller within the directive itself. The way you're doing it causes spagetti scopes. Keep the directive scope separate from parent scopes. If you want you can pass the required dependencies to a directive.
Sidharth Panwar
  • 4,606
  • 6
  • 27
  • 36
0
return {
    restrict: 'E',
    templateUrl: '/src/templates/noise/swatches.html',
    link: link,
    require: "ngDirective", //Get the controller of that directive
    link : function(scope, element, attributes, ngController){

      //With require, you say: get the controller of that directive. You can       
      //then use it as 4th parameter (ngController) 

    }

};

Note: you can pass multiple controllers

return {
    restrict: 'E',
    templateUrl: '/src/templates/noise/swatches.html',
    link: link,
    require: ["ngDirective1", "ngDirective2"], //Get the controller of that directive
    link : function(scope, element, attributes, controllers){
      var ctrl1 = controllers[0];
      var ctrl2 = controllers[1];

      //Require can be a string or, as this example, an array.

    }

};

The directive passed inside require must be in your directive. If it is not, you can say: find it on container elements with ^: require : '^ngDirective'

gr3g
  • 2,866
  • 5
  • 28
  • 52