VSO VSO - 6 months ago 26
AngularJS Question

Access Method of Parent Object From ForEach Loop

I think this is more of a javascript question than an angular question, but context was angular, so keeping it there. Basically I am trying to call the

doSomething
method. It looks like lodash's
._forEach
is creating its own scope, so I can't access
var service
using
this
, because that refers to the loop here.

So, what's the best way for me to call
doSomething
from where it is in the code below (inside the
forEach
)?

'use strict';

angular.module('app').service('fooService', function()
{

var service = {
barMethod: function(arrayOfObjects){
//this.doSomething(); - this works if not commented out,
//but I need it from within loop
_.forEach(arrayOfObjects, function (ob) {
this.doSomething();
});

},

doSomething: function(){
//do something
},

};

return service;
});

Answer

try this

var service = {
    barMethod: function(arrayOfObjects){
          var self = this
        _.forEach(arrayOfObjects, function (ob) {
            self.doSomething();
        });

    },

    doSomething: function(){
        //do something
    },

};
Comments