Search code examples
javascriptangularjscontrollers

AngularJS calling a controller from a directive


I have a model called 'user', 'user' has a controller called 'login' and a directive called 'userMenu', what I'm trying to achieve is that the userMenu directive uses the controller 'login' that's available in the module. Maybe I don't understand well how the modules and directives should work but I'm doing the following:

First, I define my controller like this:

angular.module('user', []).
controller('login', ['$scope', '$http', function($scope, $http){
    $scope.logIn = function(){
        //Do something...
    }
}

Then, in my directive...

angular.module('user', []).
directive('userMenu', function(){
    return {
    priority: 0,
    templateUrl: 'app/includes/user/menu.html',
    replace: true,
    restrict: 'A',
    controller: 'login',
    }
});

But the I get this:

Error: Argument 'login' is not a function, got undefined

Would you please guide me on the use of directives and controllers within modules?


Solution

  • The problem is that you are re-defining the user directive while preparing your directive. I presume that you wanted to register both a controller and a directive on the same module. If so you can register your directive like this:

    angular.module('user').directive('userMenu', function(){
        return {
        ...
        }
    });
    

    Notice that there is no second argument ([]) to the call of angular.module which means that you want to retrieve an instance of already defined module instead of defining a new one.