Home Ask Login Register

Developers Planet

Your answer is one click away!

nevva February 2016

Angular: require injected controller from module

I'm trying to use the require function in my custom directives. but i simply cannot make it work. This is what i've got:


var app = angular.module('main', []);
app.controller('MyController', ['$scope', function($scope){
        var random = Math.random()*10000;
    console.log('init random: ' + random);
    $scope.test = function(controllerName){
        console.log(controllerName + " " + random);

  app.directive('myDirective', function(){
      require: "^MyController",
      link: function(scope, els, attrs, req){
    app.directive('mySecondDirective', function(){
      require: "^MyController",
      link: function(scope, els, attrs, req){


<div ng-app="main" ng-controller="MyController">


all I get is this error message: Controller 'MyController', required by directive 'myDirective', can't be found!

What else do I have to do to make it work?


estus February 2016

The controllers specified in require are named after their directives, not controller names. The purpose of require is to communicate with controller instance (this) of relative directive, which will be equal to req parameter in link function.

Therefore, it can't be limited to MyController. If some abstract ng-controller controller should be required (which makes little sense because of the fragility of this condition), then it would be

require: "^ngController",

Zeeshan Hassan Memon February 2016

Need to Understand the cause -

If you want to share the same instance of a controller, then you use require.

require ensures the presence of another directive and then includes its controller as a parameter to the link function. So if you have two directives on one element, your directive can require the presence of the other directive and gain access to its controller methods. A common use case for this is to require ngModel.

^require, with the addition of the caret, checks elements above directive in addition to the current element to try to find the other directive. This allows you to create complex components where "sub-components" can communicate with the parent component through its controller to great effect. Examples could include tabs, where each pane can communicate with the overall tabs to handle switching; an accordion set could ensure only one is open at a time; etc.

In either event, you have to use the two directives together for this to work. require is a way of communicating between components.

For Further Understanding Go Here : enter link description here

Post Status

Asked in February 2016
Viewed 1,264 times
Voted 5
Answered 2 times


Leave an answer

Quote of the day: live life