Accessing a Parent Object's Method Within a ForEach Loop

While this question leans towards a JavaScript issue rather than Angular, the context remains within Angular. The problem arises when attempting to call the doSomething method from lodash's ._forEach, which creates its own scope causing an inability to access var service using this as it refers to the loop itself.

So, what would be the most effective approach for invoking doSomething from within the code snippet 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 №1

give this a shot

let myService = {
    fooMethod: function(arrOfItems){
          let that = this
        _.forEach(arrOfItems, function (item) {
            that.performAction();
        });

    },

    performAction: function(){
        //perform action here
    },

};

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

The Express-Validator failing to validate

I'm currently working on a basic program with Express. I've integrated Express-Validator to perform validations on an EJS index file. Initialization: const {check, validationResult} = require('express-validator/check'); Implementatio ...

Angular 2's solution for a persistent footer at the bottom of the page

I'm currently working on a project using Angular 2, and I'm looking to implement a sticky footer that always stays at the bottom of the page without being fixed. For reference, you can check out an example here: http://codepen.io/chriscoyier/pen/ ...

What is the designated color for highlighting an option in Next.js?

This is my first time working on a Next.js project and I see an unfamiliar option. Which selection should I choose? I plan to use JavaScript for the Next.js project, not TypeScript. Just need to figure out which option is currently selected so I can pro ...

"The interconnection between NetBeans, jQuery, and AJAX is

My issue is with a Netbeans 7.4 (also tried 7.3) project involving PHP and JavaScript where breakpoints do not work in jQuery ajax loaded pages that contain included JavaScript. I have no problem with PHP or top-level JavaScript, but for example: In index ...

A glitch occurred while attempting to load content dynamically onto an HTML page using Ajax

Attempting to dynamically load content into an HTML div is causing issues for me. Whenever I try to do so, an error pops up: Syntax error HOME. (this is the expected visible content within the div). HTML: Navigation bar: <li><a href="#" onclick= ...

What is the best way to include JSON values for specific keys using JavaScript, jQuery, or AngularJS?

Below is a sample of the json: var json = var data = [{ "a": 150 }, { "a": 50 }, { "b": 100 }, { "b": 25 }]; I aim to combine the values of "a" and "b" in a new finaljson(the desired output json), like so: var finaljson = [{ "a": 200 ...

Having trouble retrieving the value from the input field with Angular.js

I am having trouble retrieving the value from an input field using Angular.js. Below is the code explanation. Here is my controller code: $scope.shipping=0; $scope.addProductInfoData=function(billdata){ console.log('valid',$scope.shippi ...

Error encountered when using Type-Script with Vue.js and Data binding

Being relatively new to the realms of Java/TypeScript, I find myself struggling with a seemingly simple task that has consumed over three days of development time. Despite successful compiling and building processes without errors, I remain perplexed by th ...

The callback function in WordPress is executed twice

I've been working on a custom WordPress plugin that includes a form for sending data to a database. However, I've encountered an issue where every time I click the submit button, the callback function runs twice, resulting in duplicate entries in ...

retrieve the complete webpage content, encompassing the .html file, images, .js files, css stylesheets, and more

I'm currently working on a project and could use some assistance. Is there a method available to download an entire page, including the .html file, images, .js files, css, etc., using PHP, JavaScript, or AJAX? <html> <body> & ...

Refreshing data in an AngularJS page without a full refresh

Currently, I am retrieving data from the database and storing it using the following code: $scope.GetMyData = function () { //http get request here .then(function (result) { $scope.myData = result.data; }); } W ...

Monitor MongoDB for expired document date fields

I'm currently working with MongoDB and MeteorJS, and I'm wondering if there is a way to observe the value of a specific field in a document. I know we can observe document updates, creations, and removals, but I am interested in monitoring a fiel ...

Having trouble decoding invalid JSON received from the Twilio API

For the past 4 hours, I've been struggling to parse a basic JSON from Twilio. The process is as follows: A text message containing a magnet link is sent Twilio forwards the request to my serverless function in the cloud I attempt to parse the reques ...

Conflict between jquery and hoverIntent libraries

I've encountered an issue with a website that was functioning properly until we added a new form to a specific page. The form, created by another person, utilizes javascript/jQuery for processing. Since adding this form, it has caused the majority of ...

JavaScript classList.remove function experiencing inconsistencies

Take a look at this fiddle: JSFiddle The HTML code: <table class="myTable"> <tr> <th>Some text</th> <td class="align"> <span class=" someStyle">1</span>/<span class="otherStyle">15</span& ...

Just encountered an issue stating "PrismaClient cannot run in the browser" while working with [Next.js]

My initial plan was to log all the IDs of news in my database using console. However, when I executed the code, an error occurred as shown in this image. What is the best way to address and resolve this issue? https://i.stack.imgur.com/ci8G1.png ...

What is the best way to update my logo and incorporate a colored border at the bottom of my fixed header while the user is scrolling down?

After spending countless hours researching online, I've been struggling to implement header effects on scroll without using JavaScript. My goal is to achieve a simple effect where the header reduces in height, the logo changes, and a colored border is ...

Display the JQuery element that contains a child element with a specified class

On my webpage, I have a dropdown menu (ul) and I want to keep it open when the user is on the page. Specifically, I only want to display the ul item if it contains an li element with the class ".current-menu-item". The code snippet below accomplishes this ...

Sending a collection of JSON data objects to a PHP page using AngularJS

Let me illustrate the structure of my JSON data: $scope.a = [{ "email": "keval@gmail", "permissions": { "upload": "1", "edit": "1" } }, { "email": "new@aa", ...

The disappearing act of the Show/Hide Button in Sencha Touch 2.3.1: what's the

I'm running into an issue with my sencha touch app. Here is the container I have defined: { xtype: 'container', text: 'SOMETHING', height: '15%', width: '15%', ...