小编典典

在angular.forEach中无法访问变量

angularjs

我有服务

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

即使在控制器中也可访问

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

有人可以解释一下为什么在angular.foreach中无法访问“ this.list”吗?如何访问“ this.list”?


阅读 332

收藏
2020-07-04

共1个答案

小编典典

angular.forEach(请参阅http://docs.angularjs.org/api/angular.forEach)函数中的最后一个参数是的上下文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);

    }
}
2020-07-04