Within the ng-repeat loop, every switch button undergoes a status change

Utilizing ng-repeat, I have implemented a feature to display multiple content with on/off buttons. However, when toggling the off button for a specific content, all button states are being changed instead of just the selected one.

<div ng-repeat="settings in Notification.preferences | orderBy:'order'">
    <p class="notification-heading">{{settings.code}}</p>
    <div class="notification-methods">
        <span>{{settings.methods[0]}}</span>
        <div class="notification-on-off-icon">
            <i class="fa fa-toggle-on active" ng-if="status == true" ng-click="changeStatus()"></i>
            <i class="fa fa-toggle-on fa-rotate-180 inactive" ng-if="status == false" ng-click="changeStatus()"></i>
        </div>
    </div>
    <div class="notification-methods">
        <span>{{settings.methods[1]}}</span>
        <div class="notification-on-off-icon">
            <i class="fa fa-toggle-on active" ng-if="status == true" ng-click="changeStatus()"></i>
            <i class="fa fa-toggle-on fa-rotate-180 inactive"  ng-if="status == false" ng-click="changeStatus()"></i>
        </div>
    </div>
</div>

Controller:

angular.module(notification_settings_app_name)
.controller("notificationSettingsCtrl", ["$scope", '$rootScope', 'notificationSettingsService', function($scope, $rootScope, notificationSettingsService) {

    $scope.status = true;
    $scope.changeStatus = function(){
        $scope.status = !$scope.status;
    }
    notificationSettingsService.NotificationGetContent().then(function(response){ debugger;
        $scope.Notification = response;
    });

}]);

JSON Data:

{
"status" : true,
"exception" : null,
"data": {
    "methods": ["SMS","EMAIL","PUSH"],
    "preferences": [
        {
            "code": "Example 1",
            "name": "Example 1 content",
            "methods": ["SMS", "EMAIL"]
        },
        {
            "code": "Example 2",
            "name": "Example 2 content",
            "methods": ["SMS", "EMAIL"]
        },
        {
            "code": "Example 3",
            "name": "Example 3 content",
            "methods": ["SMS", "EMAIL"]
        },
        {
            "code": "Example 4",
            "name": "Example 4 content",
            "methods": ["SMS", "EMAIL"]
        }
    ]
}

}

Can anyone suggest a method to prevent all on/off buttons from changing state simultaneously? The desired behavior is for only the clicked button's state to change. Is there a way to achieve this using AngularJS?

Apologies for the delay; I forgot to mention an additional requirement. It is necessary to send a response to a URL in the following format: If, for example, the email option for Example 1 is toggled off, the response should be sent as false and vice versa.

PUT : http://URL
  {
    "category": "Example 1",
    "method": "EMAIL",
    "enabled": false
  }

Link to working Plunker

Answer №1

Appreciate the information provided, now I have a better understanding. It seems that the status indicates the existence of data on the server-side, while setting.methods controls the on/off functionality as an array. Based on my assumptions, I have made certain adjustments.

Note: Just for amusement, I decided to rearrange the positioning of the span and you can view it on this link

var app = angular.module('plunker', []);

app.controller('MainCtrl', function($scope) {
  $scope.status = true;
  $scope.changeStatus = function(settings){
        $scope.status = !$scope.status;
  };
  
  $scope.addMethod = function(setting, method){
    setting.methods.push(method);
  }
  
  $scope.removeMethod = function(setting, method){
    var index = setting.methods.indexOf(method);
    setting.methods.splice(index,1);
  }
    
    
  var response = {
        "status" : true,
        "exception" : null,
        "data": {
            "methods": ["SMS","EMAIL","PUSH"],
            "preferences": [
                {
                    "code": "Example 1",
                    "name": "Example 1 content",
                    "methods": ["SMS", "EMAIL"]
                },
                {
                    "code": "Example 2",
                    "name": "Example 2 content",
                    "methods": ["SMS", "EMAIL"]
                },
                {
                    "code": "Example 3",
                    "name": "Example 3 content",
                    "methods": ["SMS", "EMAIL"]
                },
                {
                    "code": "Example 4",
                    "name": "Example 4 content",
                    "methods": ["SMS", "EMAIL"]
                }
            ]
        }
        };
  $scope.Notification = response.data;
    
});
<!DOCTYPE html>
<html ng-app="plunker">

<head>
  <meta charset="utf-8" />
  <title>AngularJS Plunker</title>
  <link data-require="bootstrap@*" data-semver="4.0.0-alpha.2" rel="stylesheet" href="https://cdn.rawgit.com/twbs/bootstrap/v4-dev/dist/css/bootstrap.css" />
  <link data-require="fontawesome@*" data-semver="4.5.0" rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/font-awesome/4.5.0/css/font-awesome.css" />
  <script data-require="<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="97fde6e2f2e5eed7a6b9a6a7b9a7">[email protected]</a>" data-semver="1.10.0" src="https://code.jquery.com/jquery-1.10.0.min.js"></script>
  <script src="//cdnjs.cloudflare.com/ajax/libs/tether/1.3.1/js/tether.min.js"></script>


  <script data-require="bootstrap@*" data-semver="4.0.0-alpha.2" src="https://cdn.rawgit.com/twbs/bootstrap/v4-dev/dist/js/bootstrap.js"></script>
  <script>
    document.write('<base href="' + document.location + '" />');
  </script>
  <link rel="stylesheet" href="style.css" />
  <script data-require="<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="ef8e81889a838e9dc1859cafdec1dbc197">[email protected]</a>" src="https://code.angularjs.org/1.4.12/angular.js" data-semver="1.4.9"></script>

  <script src="app.js"></script>
</head>

<body ng-controller="MainCtrl">
  <div class="container">
    <div ng-repeat="settings in Notification.preferences | orderBy:'order'">
      <p class="notification-heading">{{settings.code}}</p>
      <div ng-repeat='method in Notification.methods track by $index' class="notification-methods">

        <div class="notification-on-off-icon">
          <span>{{method}}</span>
          <i class="fa fa-toggle-on active" ng-if="settings.methods.indexOf(method) != -1" ng-click="removeMethod(settings, method)"></i>
          <i class="fa fa-toggle-on fa-rotate-180 inactive" ng-if="settings.methods.indexOf(method) == -1" ng-click="addMethod(settings, method)"></i>
        </div>
      </div>

    </div>
  </div>
</body>

</html>

Answer №2

Just a heads up: If you have the ability to modify the incoming JSON structure, I have a more efficient solution for this issue (although the current solution does work, it can be enhanced with JSON structure changes).

The reason behind this is that your $scope.status is shared among all users rather than being specific to individual preferences. Take a look at this example:

var app = angular.module("sa", []);

app.controller("FooController", function($scope) {
  $scope.changeStatus = function(settings, method) {
    settings[method] = !settings[method];
  };

  $scope.isActive = function(settings, method) {
    return settings[method];
  };

  $scope.Notification = {
    "status": true,
    "exception": null,
    "data": {
      "methods": ["SMS", "EMAIL", "PUSH"],
      "preferences": [{
        "code": "Example 1",
        "name": "Example 1 content",
        "methods": ["SMS", "EMAIL"]
      }, {
        "code": "Example 2",
        "name": "Example 2 content",
        "methods": ["SMS", "EMAIL"]
      }, {
        "code": "Example 3",
        "name": "Example 3 content",
        "methods": ["SMS", "EMAIL"]
      }, {
        "code": "Example 4",
        "name": "Example 4 content",
        "methods": ["SMS", "EMAIL"]
      }]
    }
  }
});
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>

<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/css/bootstrap.min.css" integrity="sha384-1q8mTJOASx8j1Au+a5WDVnPi2lkFfwwEAa8hDDdjZlpLegxhjVME1fgjWPGmkzs7" crossorigin="anonymous">

<link href="https://maxcdn.bootstrapcdn.com/font-awesome/4.6.3/css/font-awesome.min.css" rel="stylesheet" integrity="sha384-T8Gy5hrqNKT+hzMclPo118YTQO6cYprQmhrYwIiQ/3axmI1hQomh7Ud2hPOy8SP1" crossorigin="anonymous">

<div ng-app="sa" ng-controller="FooController" class="container">

  <div class="panel panel-default" ng-repeat="settings in Notification.data.preferences | orderBy:'order'">
    <p class="notification-heading panel-heading">{{settings.code}}</p>
    <div class="notification-methods panel-body">
      <span>{{settings.methods[0]}}</span>
      
      <span class="notification-on-off-icon">
        <i class="fa fa-toggle-on fa-rotate-180 inactive" ng-class="{'fa-toggle-on active': !isActive(settings, settings.methods[0]), 'fa-toggle-off inactive': isActive(settings, settings.methods[0])}" ng-click="changeStatus(settings, settings.methods[0])"></i>
      </span>
    </div>
    
    <div class="notification-methods panel-body">
      <span>{{settings.methods[1]}}</span>
      
      <span class="notification-on-off-icon">
        <i class="fa fa-toggle-on fa-rotate-180 inactive" ng-class="{'fa-toggle-on active': !isActive(settings, settings.methods[1]), 'fa-toggle-off inactive': isActive(settings, settings.methods[1])}" ng-click="changeStatus(settings, settings.methods[1])"></i>
      </span>
    </div>
  </div>
</div>

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

Refresh the data in an existing Highstock chart with JavaScript only

I'm currently updating a website and unfortunately, I do not have access to the original code. All I am able to do is append new code at the end of it. The existing code consists of a highstock chart with specific data attributes. Here is the snippet ...

Whenever I try to send an email in Node.js, I encounter 404 errors. Additionally,

I have an Angular application with a form that makes AJAX requests. Emailing works fine, but no matter what I set the response to, I get an error for the path '/send'. I assume Node.js expects the path '/send' to render a template or da ...

What could be causing the issue of messages not displaying while incorporating connect-flash with res.locals in express.js and ejs templating?

Here are some snippets of code that may be useful. Connect-flash is designed to display messages on test1 and test2, but there seems to be an issue with displaying messages for test 3: user registration when all three tests are redirected to the same &apos ...

What causes async / await function to be executed twice?

I am currently developing a node.js application using express. In this project, I have implemented a regular router that performs the following tasks: It searches for the myID in the DB, If the myID is found, it attempts to execute the addVisit() functio ...

Samsung Galaxy S7 can interpret alphabetical parameters as numbers in a link sent via SMS

When trying to open a text message with a new message on my website using a link, I encountered an issue specifically with the Galaxy S7. The following code works on most Android phones: sms:5555555555?body=JOIN However, on the Galaxy S7, the "?body=JOIN ...

Accessing Rails controller information via a JavaScript AJAX request

In the process of developing a rails application, I have implemented code within the controller to interact with an API. Initially, I call the inventories endpoint, followed by separate calls to two other id endpoints (store_id and product_id) in order to ...

Using JavaScript to launch a new window for a specific folder

When opening a popup window with a specific URL, I typically use the following code: $("#OpenFolder").click(function () { var url = "https://stackoverflow.com"; windowObjectReference = window.open(url, "ModulesList", " ...

purging data from javascript objects

In my Node.js HTTP server, I am using 'connect' to build a web service that currently parses JSON requests into an Object, performs operations, and returns a synchronous response. The JSON data comes from an ecommerce cart and results in an Objec ...

Issues encountered when trying to use the export default syntax in Vue components

Programming Issue I attempted to execute the provided code, but unfortunately, it does not work and no output is visible in the browser. Is there an alternative method for writing code within <scripts setup> </script>? I have understood that f ...

jQuery .click() only triggering upon page load

I've been searching all over the place and I just can't seem to find a solution to my specific situation. But here's what I'm dealing with: Instead of using inline HTML onclick, I'm trying to use jQuery click() like this $(docume ...

What is the best way to display the value of a PHP variable in a JavaScript pop-up window?

Here are the scripts I have. A user will input a numerical value like 123 as a parameter in the URL, and the application will retrieve that value from MySQL and display it in the textarea. For example, if you enter "example.com/index.php?id=123" in the UR ...

Top technique for mirroring a website

Recently, I created a directory for a client's website. The site is fully operational, but the client would like a replicated version for testing and learning purposes. To create a full replica of his website, it will require hours of work to change ...

Creating synthetic data using the Faker library

I'm currently developing a script that utilizes the faker and JSON-Schema-Faker libraries to generate test data. I am specifically interested in examples involving "schema inheritance" and optional fields. For instance, I have a 'user' obje ...

No matter how hard I try, the async function within the React Component keeps returning 'Promise {<pending>}' consistently

Currently, I'm facing an issue where running an asynchronous function inside a functional component in React (NextJS) results in the function returning a pending promise: Promise {<pending>}. Oddly enough, fetching data from a dummy API works pe ...

Using jQuery to toggle visibility on click within WordPress

Looking for a way to make three buttons change color on hover and display different content when clicked? You're not alone! Despite searching through tutorials and forums, the solution remains elusive. The buttons are structured like this: <div i ...

Most effective method for detecting null or undefined values

Curious to know, what is the most efficient method for verifying if something is null or undefined within JSON arrays or objects in general? I have been utilizing if (value !== null && value !== undefined) { // Value isn't null or undefine ...

Utilizing stream-based reading and writing to execute operations in MySQL database operations

I have extracted data from table tb_project_milestones and aim to insert this projectMilestoneRow into a table tb_xyz using streams. I referred to the documentation, but couldn't figure out how to execute it. Has anyone tried reading and inserting thr ...

The value stored in $_POST['valuename'] is not being retrieved

Having recently delved into ajax, I am encountering some difficulties in making it function properly. The objective of the code is to send two variables from JavaScript to PHP and then simply echo them back as a string. However, instead of receiving the e ...

Deactivating AngularJS debug information in a gulp / typescript production compilation

What is the most effective approach to disabling debug data in a gulp production build? The recommended method for disabling debug data is: myApp.config(['$compileProvider', function ($compileProvider) { $compileProvider.debugInfoEnabled(false ...

Closing an Angular Modal Service from External Elements - Learn the Techniques

This is the official angular-modal-service Github page. If you're looking for some examples, check out the angular-modal-service examples here. For my current project, I am working on developing a "Custom Modal" without relying on Bootstrap. Here&ap ...