Luís Costa
Luís Costa

Reputation: 23

Inject service in controllers using angularjs

I'm creating an app using angularjs, I have two controllers, and one service (all in separated files). My problem is that I can't inject the service in the controllers. I used the service in the same file as the controller and it worked, but I want it in separated files to share data between controllers.

This is one of my controllers

     var app = angular.module('cloudpear', ['ngRoute','ServiceUser']);

    app.controller('login',['$scope','$location','$window', function(ServiceUser,$scope,$location,$window){
.....
}]);

This is my service

var app = angular.module('service', []);

app.factory('ServiceUser',function(){
    var user=[];

    return{
        add: add,
        get: get
    }

    function add(item){
        user.push(item);
    }

    function get(){
        return user;
    }

    return user;
});

I get this error:

Uncaught Error: [$injector:modulerr] http://errors.angularjs.org/1.6.4-build.5327+sha.233f47b/$injector/modulerr…20(https%3A%2F%2Fcode.angularjs.org%2Fsnapshot%2Fangular.min.js%3A22%3A179)

Can you tell me what I'm doing wrong, I've searched everywhere and tried multiple solution, but nothing worked!

Upvotes: 0

Views: 44

Answers (1)

Satpal
Satpal

Reputation: 133403

As you have define a separate module for service, you need to inject service module in the cloudpear module declaration.

var app = angular.module('cloudpear', ['ngRoute','service']); 
                                                 //^^^^^^^^^^ instead of ServiceUser

Then need to inject service in controller

app.controller('login',['ServiceUser', '$scope','$location','$window',function(ServiceUser, $scope,$location,$window){

Upvotes: 2

Related Questions