Exploring ways to implement identical 'if' conditions across various controllers in AngularJS

Is there a way to avoid repeating the if condition in multiple controllers? How can I simplify this process?

MainController.js :

 $scope.responseData.forEach(function(card) {

    switch (card.Category) {
        case 'Apple':
            console.log("Apple");
            break;
        case 'Google':
            console.log("Google");
            break;
        case 'Microsoft':
            console.log("Microsoft");
            break;
        case 'Amazon':
            console.log("Amazon");
            break;
    }
});

FirstController.js :

$scope.responseData.forEach(function(card) {
    switch (card.Category) {
        case 'Apple':
            console.log("Apple");
            break;
        case 'Google':
            console.log("Google");
            break;
        case 'Microsoft':
            console.log("Microsoft");
            break;
        case 'Amazon':
            console.log("Amazon");
            break;
    }
});

SecondController.js :

$scope.responseData.forEach(function(card) {

   switch (card.Category) {
        case 'Apple':
            console.log("Apple");
            break;
        case 'Google':
            console.log("Google");
            break;
        case 'Microsoft':
            console.log("Microsoft");
            break;
        case 'Amazon':
            console.log("Amazon");
            break;
    }

});

How can I centralize this condition and reuse it across multiple controllers?

Answer №1

To address your query, one effective method is to utilize a factory. I have provided an illustrative example below: https://jsbin.com/veregejawo/1/edit?html,js,console,output Hopefully, this demonstration proves helpful: HTML:

<!DOCTYPE html>
<html>
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.6.9/angular.min.js"></script>
<body ng-app="app">

<div ng-controller="mainController">
  {{controller}}
  <br>
  <button ng-click="testfactory('Apple')">Apple</button>
</div>

<div ng-controller="firstController">
  {{controller}}
  <br>
  <button ng-click="testfactory('Google')">Google</button>
</div>

<div ng-controller="secondController">
  {{controller}}
  <br>
  <button ng-click="testfactory('Microsoft')">Microsoft</button>
</div>

<script>

</script>

</body>
</html>

Controller:

angular.module('app', []);
angular.module('app').factory('ifFactory', function () {

    var factory = {};
    factory.checkIf = function (param) {
        if (param == 'Apple') {
           console.log("Apple");
         } else if (param == 'Google') {
           console.log("Google");
         } else if (param == 'Microsoft') {
           console.log("Microsoft");
         } else if (param == 'Amazon') {
           console.log("Amazon");
         }
    };
    return factory;

});

angular.module('app').controller('mainController', ['$scope', 'ifFactory',
    function ($scope, ifFactory) {
      $scope.controller = "mainController";

      $scope.testfactory = function(param){
        ifFactory.checkIf(param);
      }
    }
]);

angular.module('app').controller('firstController', ['$scope', 'ifFactory',
    function ($scope, ifFactory) {
      $scope.controller = "FirstController";

      $scope.testfactory = function(param){
        ifFactory.checkIf(param);
      }
    }
]);

angular.module('app').controller('secondController', ['$scope', 'ifFactory',
    function ($scope, ifFactory) {
      $scope.controller = "SecondController";

      $scope.testfactory = function(param){
        ifFactory.checkIf(param);
      }
    }
]);

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

Concealing option value based on ng-if conditions in AngularJS: A guide

I am designing an Input form with two input fields that need to be compared and values displayed if a certain condition is met. The input fields are: <td class="td_label"><label>Client Age :</label></td> <td class="td_input"> ...

Error Alert: Request missing connection details while trying to connect to Sql server via express.js

I am currently utilizing the most recent versions of node, express, and mssql module. My objective is to establish a connection with the local instance of SQL Server 2014 through express.js. Following the guidelines provided in the official documentation, ...

Variations in how words are organized within a sentence

Can you help me devise an algorithm to identify all possible combinations of word groupings in a sentence without changing the order of the words? For example, for the sentence "the test case phrase," the various combinations would include: ['the te ...

Update the default payment method to Braintree's drop-in user interface for seamless checkout

I'm currently using Brain-tree as my payment gateway and utilizing the drop-in UI feature. Within the drop-in UI, there is an option to change the payment method. However, after changing the payment method, it does not set the new card as the default ...

What are some ways to streamline and improve the readability of my if/else if statement?

I've created a Rock Paper Scissors game that runs in the console. It currently uses multiple if/else if statements to compare user input against the computer's selection and determine a winner. The code is quite lengthy and repetitive, so I' ...

Updating a table dynamically after a form submission using jQuery, Ajax, and PHP without needing to refresh the page

My current setup involves an ajax form along with a table. Here is the ajax code I am using: $(function () { $(".submitann").click(function () { var title = $("#title").val(); var announcement = $("#announcement").val(); var d ...

Storing multiple textbox values in a single column in PHP

I am using JavaScript to show multiple text boxes when the add button is clicked, but I am unsure of how to store the values of these text boxes in a single column of a database table. Below is my form input code and JavaScript for adding a number of text ...

Issues with Jquery and revslider functionality in React.js are causing problems

Just getting started with react.js and diving into the world of react development. Encountering an issue while converting static HTML to react.js where jQuery scripts only execute after manually refreshing the page, causing a slowdown in React speed. T ...

How to retrieve the row index from a table using JavaScript

This question has cropped up numerous times, and despite trying various solutions suggested before, none of them seem to be effective in my case. Within a modal, I have a table where users can make changes that are then used to update the database. The ta ...

Utilizing React: Incorporating classes to elements with innerHTML

Is there an efficient way to determine if a table cell contains innerHTML and apply a class accordingly? I have a large table with numerous cells that need to be handled dynamically. The cell content is set using dangerouslySetInnerHTML, as shown below: ...

Bringing in manageable RxJS operators

RxJS 5.5 has undergone a significant change and has introduced lettable operators to replace the traditional operators we were using previously. In the article, there is a note that states: Lettable operators can now be imported from rxjs/operators, bu ...

Monitoring alterations in dynamically produced input fields using jQuery

My code currently generates multiple input fields dynamically, each related to a specific database record. I utilize PHP's dynamic array notation ('[]') to store the input values. Everything is working smoothly up to this point... Now, I am ...

Automatic switching between Bootstrap 5 tab panes at precise time intervals

Is there a way to have the Bootstrap 5 tab-pane automatically switch between tabs at set intervals, similar to a Carousel? I found a code snippet on this link, but it appears to be outdated and only works for Bootstrap 3. Could someone assist me in updati ...

Optimizing Google e2e testing using Protractor

Improving login efficiency is necessary to enhance the speed of executing e2e tests. At present, after every test, the Chrome browser shuts down, requiring a new login session for each subsequent test. What changes can be made to address this issue? Any ...

How can I set the initial Number of SMS to 1 when the characters are less than or equal to 160?

I am working on a jQuery code that displays the current number of characters being typed, the remaining characters, and also the number of SMS. The rule is that any value between 0 and 160 represents 1 SMS, while any value above that but less than 321 repr ...

Guide on merging two objects in AngularJS

Is there a way to combine two requests in angularJS for employee and Allowance info using the empID as the link between them, as shown in Level 3? Level 1 : Employee Information [ { "empID": "PC145", "fullName": "Lamin L Janneh", "Job": ...

"Troubleshooting the issue of AngularJS $http patch request failing to send

The information is successfully logged in the console when passed to replyMessage, but for some reason, the API does not seem to be receiving the data. Is the input field perhaps empty? replyMessage: function(data) { console.log(data); ...

How can I use D3.js to form a circular group in an organization structure, link it with a circular image, and connect

Is it possible to create a radial grouped circle using d3.js, similar to the image below: https://i.sstatic.net/1Hwd2.jpg I have written some code as shown below. However, I am facing challenges in connecting every circle with a curved line and displayi ...

Building a dynamic Single Page Application with the power of Durandal

Our vision for the single-page app is to create a dynamic system where users can personalize their views and widgets in real-time. Instead of predefined views and viewmodels on the server, we want end-users to have the flexibility to define and customize w ...

I'm having some trouble with this search filter in Vue 2 - is it failing to display the items as expected

After struggling with this issue for over a week, I've hit a roadblock and need some assistance. I'm currently working on implementing a search filter in Vue 2 with Vuetify, but something isn't quite right. Here's a snippet of the sea ...