lmenus
lmenus

Reputation: 613

Passing an array from service to controller

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

Upvotes: 0

Views: 1941

Answers (3)

André
André

Reputation: 156

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);
});

Upvotes: 0

michelem
michelem

Reputation: 14590

Just change test.arraywith test:

JSFiddle

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

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

Upvotes: 1

Hylianpuffball
Hylianpuffball

Reputation: 1561

(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;
    };
})

Upvotes: 2

Related Questions