adam
adam

Reputation: 555

Angular directives Controller not found by require

here's the problem, i'm trying to split my html by using a directive for render a sub header.

In the sub header, i'm doing some logic to render some buttons. All the logic used for that is coded in the controller of this view.

So i wrote a directive to create an element for my sub header:

 angular.module('myApp')
  .directive('subHeader', ['ServiceOne','ServiceTwo',
  function(ServiceOne, ServiceTwo){
    return{
      restrict: 'E',
      require: '^MyCtrl',
      link: function(scope, element, attrs, ctrl){
          console.log(ctrl);

         // Logic for buttons in sub header

      },
      templateUrl: '--here my path to the .html template--'
    };
  }]);

The html template is rendered fine in the view fine, so i try to move the functions for the logic present in my sub header in the link method. But i'm not able to log the existing controller.

I just want to add that i am requiring the controller because the logic in sub header depends on the data retrived by that controller.

What am i missing or what am i doing wrong?

Upvotes: 0

Views: 624

Answers (1)

Yashika Garg
Yashika Garg

Reputation: 2366

In directives we use "controller" and "controllerAs" not "require". "controller" - the actual name of your controller in string or controller function itself. "controllerAs" - the alias name of your controller which you can use in your html view

 angular.module('myApp')
  .directive('subHeader', ['ServiceOne','ServiceTwo',
   function(ServiceOne, ServiceTwo){
    return{
      restrict: 'E',
      controller: 'MyCtrl',
      link: function(scope, element, attrs, ctrl){
        console.log(ctrl);

        // Logic for buttons in sub header

       },
       templateUrl: '--here my path to the .html template--'
    };
 }]);

 angular.module('myApp').controller("MyCtrl", function($scope){
    //Do your stuff
 });

OR

angular.module('myApp')
  .directive('subHeader', ['ServiceOne','ServiceTwo',
   function(ServiceOne, ServiceTwo){
    return{
      restrict: 'E',
      controller: function($scope)(){
       // Do your stuff
      },
      controllerAs: 'MyCtrl',
      link: function(scope, element, attrs, ctrl){
        console.log(ctrl);

        // Logic for buttons in sub header

       },
       templateUrl: '--here my path to the .html template--'
    };
 }]);

Upvotes: 1

Related Questions