Strategies for streamlining repetitive code within a closure in Angularjs

We are currently utilizing Angularjs 1x and I am in the process of refactoring some repetitive code within an Angularjs filter. However, I am facing challenges in getting it to function correctly. It should be a straightforward task.

Our standard approach involves using filters with an Anonymous self-executing function, similar to the code snippet provided below. Within a for loop, there are if/else blocks containing duplicated code that I aim to streamline by creating a reusable function. Despite my efforts, I am unable to successfully invoke this function. How can I resolve this issue?

(function() {
  //Named function
  function abc(Input){
    return function(value){
      for(var i=0; i<3; i++){
        if(w){
            //Duplicate code here
         } else if(x){
            //Duplicate code here
         } else if(y){
            //Duplicate code here
         } else if(z)
       }
     }
  }
}
))();

Here is an example resembling the repeated code, which remains unchanged within each block. We have implemented a dedicated service for managing labels.

if(Input[i].fpwInd === 'Y' && fpw.plan === 'State') {
    fpwValues.push(weblService.returnLabel("yes", $rootScope.label));
    break;
}else if(Input[i].fpwInd === 'N' && fpw.plan === 'Another State') {
    fpwValues.push(weblService.returnLabel("no", $rootScope.label));
    break;
}

This revised code snippet demonstrates the final solution:

(function() {

  var fwp = function(input, plan){
    if(input == "value" && plan == "somevalue")
    fpwValues.push(weblService.returnLabel("yes", $rootScope.label));
    //Additional logic for if/else statements goes here...
};  

  function abc(){
    return function(value){
      for(var i=0; i<3; i++){
        if(w){
            fwp(input, plan);
            break;
         } else if(x){
            fwp(input, plan);
            break;
         } else if(y){
            fwp(input, plan);
            break;
         } else if(z)
       }
     }
  }
}
))();

Answer №1

Using your second example as a starting point, is it possible to implement something similar to this?

Providing more information would be greatly beneficial - what is preventing you from correctly calling the function? Are there any specific errors occurring?

(function() {
function getLabelStrForIndPlan(ind, plan) {
  if (ind === 'Y' && plan === 'State') {
    return 'yes';
  }
  else if (ind === 'N' && plan === 'Another State') {
    return 'no';
  }
}

function abc(Input){
  return function(value){
    for(var i=0; i<3; i++){
      var fpwInd = Input[i].fpwInd;
      var label = getLabelStrForIndPlan(fpwInd, fpw.plan);

      if (label) {
        fpwValues.push(weblService.returnLabel(label, $rootScope.label));
        break;
      }
    }
  }
}
})();

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

Issue encountered while trying to execute Reapp project demo

As I embark on setting up my initial Reapp project, I encounter a roadblock right at the start. A blank screen greets me, accompanied by a console error stating that main.js is not found (error 404). Upon executing reapp run -d, the following errors manif ...

Creating a new window using JavaScript with custom settings

Is it possible to create a window that opens when double clicking an icon on the desktop? I want this window to have specific dimensions and no menu bar or scrollbar. This is what my current code looks like: document.onload(openWin()); function openWin( ...

Encountering a 404 error in html5Mode when attempting to refresh a page while using AngularJS version 1.0

After reading several posts on this topic, I realize that I may not have the necessary expertise to fully grasp what needs to be done. In my AngularJS 1.0.7 web application, I recently enabled html5Mode to enhance the appearance of my URLs. While this cha ...

Performing a Node.js PUT call with specified parameters

Attempting to send a PUT request using the 'request' function to the following URL: request({ uri: 'http://apiurl.url/1.0/data?token=' + APItoken, method: 'PUT', data: [{ ...

Using the && operator for conditional rendering in a React return statement

How should I format my return statement in a class component when using the && operator in the condition like this: if (x === null && y === null) If the condition is met, display this HTML: <div className="col-12"> <SomeComponent /> < ...

Having trouble modifying a nested object array within a treeview component in Reactjs

Thanks for your help in advance! Question: I'm having trouble updating a nested object of an array in a treeview using Reactjs. Please refer to the code and sandbox link below: https://codesandbox.io/s/cocky-leakey-ptjt50?file=/src/Family.js Data O ...

Make toggleClass show up smoothly without disappearing

I'm currently working with jQuery's toggleClass() method and I want to achieve a fade-in effect without the corresponding fade-out animation. Using the "duration" attribute applies the same duration for both actions, which is not what I want. I w ...

What is the best way to add child elements to existing elements?

When it comes to creating elements with jQuery, most of us are familiar with the standard method: jQuery('<div/>', { id: 'foo', href: 'http://google.com', }).appendTo('#mySelector'); However, there ar ...

Can data be transferred from one website to another without the use of an API?

I am a newcomer to the world of web development with basic knowledge of JS, Node, Express, Mongoose, and MongoDB. I have an exciting idea for a web application that would function like a spreadsheet, gathering user inputs to generate an output. The unique ...

How can SQL data be loaded following the selection from a dropdown menu?

I have a pressing query that I need assistance with. I am aiming to achieve a certain task, but due to lack of prior experience in this area, I am unsure about how to proceed. My current situation involves populating a dropdown menu with names retrieved f ...

Having trouble loading the login.html page in ng-view with AngularJS, UI Bootstrap, and MVC Frontend framework

I am currently developing an MVC project using Maven. On the backend side, I am utilizing the Spring Boot framework with a Tomcat server, MySQL database, hibernate for database binding, and extending dao to CrudeRepository. There is no need for a service ...

Why does it fire off numerous requests even though I only called it once?

Everything seemed to be working fine with my project. However, I noticed in the console network that one of my GET requests is being sent twice even though I only triggered it once. View network console here If I comment out the entire created function co ...

JavaScript code that involves manipulating dates within a nested loop

I'm currently developing a booking system where the pricing varies based on seasons that recur annually. The overall functionality is working smoothly, however, I am encountering difficulties with handling the recurring seasons. I have implemented mom ...

Exploring the power of developing AngularJS applications using Typescript and the app

I am currently working on a basic application that utilizes Typescript and AngularJS. In my app, I have used app.js to register my controller and some route parameters: /// <reference path="../scripts/typings/angularjs/angular.d.ts" /> /// <refer ...

The ng-disabled directive is functioning properly, however it is not having any impact on the disabled attribute in

Having an issue with enabling or disabling a button based on the selection of a certain string from a dropdown menu. HTML <select ng-change="checkType()" ng-options="sth in sth for things"></select> <input ng-disabled="{{toggleDisable}}" ...

Highest Positioned jQuery Mobile Section

Requesting something a bit out of the ordinary, I understand. I currently have a jQueryMobile page set up with simplicity: <div data-role="page" class="type-home" id="home"> <div data-role="header" data-theme="b"> <h1>Our To ...

How do I access and read a map within an array from Firebase using ReactJS?

I have an array that contains a map with two values: title and content. https://i.stack.imgur.com/WLWVG.png I am trying to read all the values in the array as if it were a map. However, I have attempted this code without success. Can anyone assist me? {d ...

Provide a response containing JSON data extracted from an HTML file

I am looking for a way to create a simple REST API using a hosting site that only allows hosting of HTML files along with JavaScript files. I want to be able to send POST/GET requests and receive JSON data in response. For instance, when making a GET requ ...

The radio input is not being properly checked using ng-checked in Angular

The ng-checked attribute is causing issues in the application, specifically with radio buttons. It seems to be working fine for checkboxes but not for radio buttons. <input type="radio" class="radio" name="job_class_radio" ng-checked="key===jobClassDat ...

Guide on removing material-ui from your project and updating to the newest version of MUI

I need to update my React app's material-ui package to the latest version. Can someone provide instructions on how to uninstall the old version and install the new MUI? UPDATED: In my package.json file, the current dependencies are listed as: ...