【问题标题】:variable is not accessible in angular.forEach变量在 angular.forEach 中不可访问
【发布时间】:2013-02-07 09:53:09
【问题描述】:

我有服务

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”?

【问题讨论】:

    标签: javascript foreach angularjs


    【解决方案1】:

    在 foreach 中无法访问 this.list 的原因是该函数调用的上下文已更改。它在execute 方法中工作,因为该方法与列表属于同一上下文。

    由于所有闭包,我会将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
            });
        }
    }
    

    这是一个比将上下文作为 foreach 方法调用的一部分传递的更通用的解决方案,并且可以在其他与闭包相关的情况下工作。

    【讨论】:

      【解决方案2】:

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

      【讨论】:

      • 谢谢,角度文档对如何将范围变量注入循环一无所知。
      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2015-07-21
      • 1970-01-01
      • 1970-01-01
      • 2023-03-15
      • 2019-10-27
      • 1970-01-01
      相关资源
      最近更新 更多