0

I cannot seem to figure out how to pass an array from service to a controller.

I have a simple service

.service('test', function() {
    var array = []

    return array;
})

And a controller where I call this function when a button is pressed

$scope.testArray = function() {
    $scope.test = test.array;

    console.log("test: ", $scope.test);
};

I get an error test is undefined. Can anyone explain to me please why this doesn't work and how to fix it? I tried storing that array in a separate object but no luck either. THanks

lmenus
  • 604
  • 9
  • 27
  • 1
    Are you injecting your service into your controller? – Anonymous Sep 05 '15 at 16:46
  • Yes, this is my controller -> .controller('TestCtrl', ['test', function(test) { <- there is a lot more data but I omitted that as I don't think it would be relevant? – lmenus Sep 05 '15 at 16:49

3 Answers3

2

(See also: this SO question about Angular providers)

A service should put properties directly on this. So instead of

.service('test', function() {
    var array = [];

    return array; 
})

try

.service('test', function() {
    this.array = [];
})

(code style notwithstanding; many would suggest preferring function access over direct object access)

.service('test', function() {
    var array = [];
    this.getArray = function(){
        return array;
    };
})
Community
  • 1
  • 1
Hylianpuffball
  • 1,553
  • 10
  • 13
  • Thanks a lot! I put it like you showed in the last example and then just tried console.log(test.getArray()); and it works! Can you tell me why wasn't my solution working and this function solved it? – lmenus Sep 05 '15 at 17:02
1

Just change test.arraywith test:

JSFiddle

.controller('youCtrl', ['$scope', 'test', function ($scope, test) {
    $scope.testArray = function() {
       $scope.test = test;

       console.log("test: ", $scope.test);
    };
});
michelem
  • 14,430
  • 5
  • 50
  • 66
  • Tried this, doesn't work for me. I might be tripping out already, it is a part of an Ionic app if that might matter. – lmenus Sep 05 '15 at 16:52
  • Thanks guys now it works too, this one return object to me and the suggestion above the array so both are good. thanks! – lmenus Sep 05 '15 at 17:03
0

Add the array variable to your service.

angular.module('moduleName').service('test', function() {
  this.array = [];
});

Inject your service into your controller.

angular.module('moduleName').controller('controllerName', function(test) {
  $scope.test = test.array;

  console.log("test: ", $scope.test);
});
André
  • 156
  • 1
  • 10