简体   繁体   中英

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!

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){

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM