user3736336
user3736336

Reputation: 137

Call a function in a controller in another module in AngularJS

I am having trouble calling a function in another controller that is in another module. I don't know if this is possible, but this is what I have now:

angular.module('search.controllers', ['socket.services', 'recipe.controllers'])
    .controller('SearchCtrl', ['$scope', '$state', 'socketService', 'recipeCtrl', 
        function($scope, $state, socketService, recipeCtrl) {
            recipeCtrl.setRecipe({});
        }
]);

angular.module('recipe.controllers', [])
    .controller('recipeCtrl', 
        function($scope) {
            this.onRecipeSelect = function(recipe) {
                console.log(JSON.stringify(recipe));
            }
        }
    );

This is giving me the error:

Unknown provider: recipeCtrlProvider <- recipeCtrl <- SearchCtrl

Anyone know how to accomplish what I am trying to do?

Upvotes: 1

Views: 2091

Answers (1)

Luiz
Luiz

Reputation: 542

Controllers can't be injected, so it simple does not work. You need to create a service with your function and inject this service.

If you need to exchange data between controllers the best option is to use events but your controllers need to be nested in order to communicate via scopes.

One last resource should use rootScope and watch for a value, but its not recommended to do it.

Upvotes: 3

Related Questions