notAChance
notAChance

Reputation: 1430

Angular Service can set data from one controller but not the other

I have a module and two controllers :

var module = angular.module("app", ["agGrid", "ngAnimate", "ngSanitize", "ngDialog"])


module.controller("mainCtrl", ["$scope", "dataService","$timeout","dateFilter","ngDialog", "$http", function ($scope, $http, $timeout, dateFilter, ngDialog, dataService) {
}]);


module.controller("modalCtrl", ["$scope", "ngDialog", "dataService", function ($scope, ngDialog, dataService) {


$scope.printEntity = function () {
    console.log(dataService.getEntityArray());
}

}]);

And a service:

 module.factory("dataService", function () {

var entityArrayService = [];

return {
    setEntityArray: function (entityArray) {
        entityArrayService = entityArray;
    },
    getEntityArray: function () {
        return entityArrayService;
    }

};

});

I can call dataService.setEntityArray(array) from inside my SECOND controller, but when i try to call this from my first controller it tells me dataService.setEntityArray is not a function

Upvotes: 1

Views: 95

Answers (2)

hsz
hsz

Reputation: 152236

You have invalid order of the variables in the first controller definition. It should be:

function ($scope, dataService, $timeout, dateFilter, ngDialog, $http)

Upvotes: 1

dfsq
dfsq

Reputation: 193261

The order of dependency injections is incorrect. Arguments in the controller function must repeat the order of the elements in the array. In your case dataService is the second argument:

module.controller("mainCtrl", ["$scope", "dataService","$timeout","dateFilter","ngDialog", "$http", function ($scope, dataService, $timeout, dateFilter, ngDialog, $http) {
}]);

Upvotes: 2

Related Questions