简体   繁体   中英

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

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

Just change test.array with test :

JSFiddle

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

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

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

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