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

2
  • 1
    Are you injecting your service into your controller? Commented Sep 5, 2015 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? Commented Sep 5, 2015 at 16:49

3 Answers 3

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;
    };
})
Sign up to request clarification or add additional context in comments.

1 Comment

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

2 Comments

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.
Thanks guys now it works too, this one return object to me and the suggestion above the array so both are good. thanks!
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);
});

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.