variable is not accessible in angular.forEach

后端 未结 2 1680
慢半拍i
慢半拍i 2021-01-01 13:27

I have a service

app.service(\'myService\', function() {
    this.list = [];
    this.execute = function() {
        //this.list is reachable here
        a         


        
2条回答
  •  时光说笑
    2021-01-01 13:46

    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.

提交回复
热议问题