Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

variable is not accessible in angular.forEach

I have a service

app.service('myService', function() {
    this.list = [];
    this.execute = function() {
        //this.list is reachable here
        angular.forEach(AnArrayHere, function(val, key) {
           //this.list is not reachable here
        });
    }
}

even in controller its accessible

function Ctrl($scope, myService) {
    $scope.list = myService.list;
}

Can someone explain me why "this.list" is not reachable within the angular.foreach and how can I access to "this.list" ?

like image 541
Vural Avatar asked Feb 21 '13 21:02

Vural


2 Answers

The last parameter in the angular.forEach (See http://docs.angularjs.org/api/angular.forEach) function is the context for this. So you'll want something like this:

app.service('myService', function() {

    this.list = [];

    this.execute = function() {

        //this.list is reachable here

        angular.forEach(AnArrayHere, function(val, key) {
           //access this.list
        }, this);

    }
}
like image 86
dnc253 Avatar answered Nov 08 '22 19:11

dnc253


The reason this.list is not accessible in the foreach is because the context for that function call has changed. It works inside the execute method as that method is part of the same context as list.

Due to all the closures I would assign the this context to another variable that you can then call later on. Something like this:

app.service('myService', function() {

    var self = this;
    self.list = [];

    self.execute = function() {
        //this.list and self.list are reachable here
        angular.forEach(AnArrayHere, function(val, key) {
           //self.this == this.list
        });
    }
}

This is a slightly more general solution than passing the context as part of the foreach method call and would work in other closure related situations.

like image 6
Coin_op Avatar answered Nov 08 '22 20:11

Coin_op