本文介绍了变量在 angular.forEach 中不可访问的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有服务

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

谁能解释一下为什么在 angular.foreach 中无法访问this.list"以及如何访问this.list"?

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

推荐答案

angular.forEach 中的最后一个参数(参见 http://docs.angularjs.org/api/angular.forEach) 函数是 this 的上下文.所以你会想要这样的东西:

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

    }
}

这篇关于变量在 angular.forEach 中不可访问的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

07-23 03:19
查看更多