1

I'm trying to extend a directive by passing controllers. I'm able to grab the parent directive's controller through require , but I also want to define a controller on the extended controller.

.directive('smelly', function(){
  return {
    restrict: 'E',
    controller: function(){
      this.doWork = function(){ alert('smelly work'); };
    },
    link: function($scope, $element, $attributes, controller){     
      $element.bind('click',function(){
        controller.doWork();
      });
    }
  };
})
.directive('xtSmelly', function(){
  return {    
    controller: function(){
      this.name = "brian";
    },
    require: 'smelly',
    link: function($scope, $element, $attributes, smellyController){
      smellyController.doWork = function(){
        alert('xt-smelly work by: ' + xtSmellyController.name);
      };
    }
  };
})

HTML
<smelly xt-smelly>click me</smelly>  

How can I access xtSmellyController.name?

2 Answers 2

1

You can use the $scope variable, both controllers will have access to that

return {    
controller: function($scope){
  $scope.name = "brian";
},
require: 'smelly',
link: function($scope, $element, $attributes, smellyController){
  smellyController.doWork = function(){
    alert('xt-smelly work by: ' + $scope.name);
  };
}

};

Example: http://plnkr.co/edit/dYIr36lKtnybxvkUlOJ1?p=preview

Sign up to request clarification or add additional context in comments.

1 Comment

Hmm, it works, but is it the right way? Doesn't it ruin separation of concerns by throwing it into the scope?
1

require can take an array, the fourth arg in the link function then also becomes an array with the requested controllers in the same order as specified in the require array

.directive('smelly', function(){
  return {
    restrict: 'E',
    controller: function(){
      this.doWork = function(){ alert('smelly work'); };
    },
    link: function($scope, $element, $attributes, controller){     
      $element.bind('click',function(){
        controller.doWork();
      });
    }
  };
})
.directive('xtSmelly', function(){
  return {    
    controller: function(){
      this.name = "brian";
    },
    require: ['smelly', 'xtSmelly'],
    link: function($scope, $element, $attributes, controllers){
      var smellyController = controllers[0];
      var xtSmellyController = controllers[1];
      smellyController.doWork = function(){
        alert('xt-smelly work by: ' + xtSmellyController.name);
      };
    }
  };
})

HTML
<smelly xt-smelly>click me</smelly>  

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.