JavaScript / AngularJS - Efficient Boolean Switching

My group of Boolean variables can toggle other variables to false when set to true.

I am looking for a clean pattern for this approach, especially since the number of boolean variables may increase.

angular.module("app", [])
  .controller("controller", function($scope) {
    $scope.a = true;
    $scope.b = false;
    $scope.c = false;

    $scope.toggleA = function() {
      $scope.a = true;
      $scope.b = false;
      $scope.c = false;
    }
    
    $scope.toggleB = function() {
      $scope.b = true;
      $scope.a = false;
      $scope.c = false;
    }
    
    $scope.toggleC = function() {
      $scope.c = true;
      $scope.b = false;
      $scope.a = false;
    }
  });
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>

<div ng-app="app" ng-controller="controller">
  <button ng-click="toggleA()">A is {{a}}</button>
  <button ng-click="toggleB()">B is {{b}}</button>
  <button ng-click="toggleC()">C is {{c}}</button>
</div>

Answer №1

When considering the various applications of these variables, it becomes clear that having multiple interdependent variables is not practical. It would be more efficient to represent the current state using a single variable that can accommodate more than just two values:

angular.module("app", [])
  .controller("controller", function($scope) {
    $scope.current = 'a';
  });
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>

<div ng-app="app" ng-controller="controller">
  <button ng-click="current = 'a'">A is {{ current == 'a' }}</button>
  <button ng-click="current = 'b'">B is {{ current == 'b' }}</button>
  <button ng-click="current = 'c'">C is {{ current == 'c' }}</button>
</div>

Answer №2

Have you considered trying a solution like this instead:

angular.module("app", [])
  .controller("controller", function($scope) {
    $scope.x = 'a';

    $scope.toggle = function(x) {
      $scope.x = x;          
    }        
  });
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>

<div ng-app="app" ng-controller="controller">
  <button ng-click="toggle('a')">A is {{x === 'a'}}</button>
  <button ng-click="toggle('b')">B is {{x === 'b'}}</button>
  <button ng-click="toggle('c')">C is {{x === 'c'}}</button>
</div>

Answer №3

'An effective way to manage boolean values is by using an array as a container and creating a single function to toggle them. Take a look at the following example.

angular.module("app", [])
  .controller("controller", function($scope) {
    $scope.keys = {
      a: true,
      b: false,
      c: false
    };

    $scope.toggle = function(change_key) {
      for (var key in $scope.keys)
        if ($scope.keys.hasOwnProperty(key))
          if (key === change_key)
            $scope.keys[key] = true;
          else
            $scope.keys[key] = false;
    }
  });
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>

<div ng-app="app" ng-controller="controller">
  <button ng-click="toggle('a')">A is {{keys.a}}</button>
  <button ng-click="toggle('b')">B is {{keys.b}}</button>
  <button ng-click="toggle('c')">C is {{keys.c}}</button>
</div>

Answer №4

If you're not sure what your next step should be, give this a try as it might offer a good solution.

angular.module("app", [])
  .controller("controller", function($scope) {
    $scope.keys = [ 
             {"name":"a","value":true},
             {"name":"b","value":false},
             {"name":"c","value":false}
    ];

    $scope.toggle = function(key) {
       key.value = !key.value;
    }
  });
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>

<div ng-app="app" ng-controller="controller">
  <button ng-repeat="key in keys" ng-click="toggle(key)">{{key.name}} is {{key.value}}</button>
</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

Utilizing tag keys for inserting text and adjusting text sizes within a Web application

Creating an online editing interface for coursework where keyboard events are used. The goal is to have the tab key insert text, while also reducing the size of the text on that line. However, upon using getElementById, an error message pops up stating: ...

Having problems with route navigation in Angular/Rails when using multiple layouts

Currently, I am in the process of building an AngularJS application that connects to a RoR backend. However, I have encountered an issue when working with multiple layouts. The application is designed to display one layout for unauthenticated users and swi ...

Retrieve the XML document and substitute any occurrences of ampersands "&" with the word "and" within it

The XML file is not being read by the browser due to the presence of ampersands represented as "&". To resolve this, I am looking to retrieve the XML file and replace all instances of "&" with "and". Is this achievable? Despite attempting to use t ...

Unable to access the 'fn' property of undefined in Handlebars causing a TypeError

I encountered an issue with my custom handlebars helper. When I fail to define values for the parameters, I receive the following error message. module.exports = function(src, color, classatr, options) { if (typeof src === 'undefined') src ...

Implementing a persistent header on a WordPress site with Beaver Builder

My website URL is: . I have chosen to use beaver builder for building and designing my website. I am in need of a fixed header that can display over the top of the header image. Here is the code snippet that I currently have: <div id="header">html ...

Looking for a quick guide on creating a basic RESTful service using Express.js, Node.js, and Mongoose?

As a newcomer to nodejs and mongoDB, I've been searching high and low on the internet for a tutorial that combines express with node and mongoose. What I'm specifically looking for is how to use express's route feature to handle requests and ...

Having trouble finding module: Unable to locate 'fs' - yet another hurdle with NextJS

Trying to access a JSON file located one directory above the NextJS application directory can be tricky. In a standard JavaScript setup, you might use the following code: var fs = require('fs'); var data = JSON.parse(fs.readFileSync(directory_pat ...

Trouble with updating Angular Js ng-model within a nested function

I am encountering an issue with the code in my controller: appControllers.controller('myCtrl', [ '$scope', function($scope) { $scope.timeFreeze = false; $scope.ws = new WebSocket("ws://localhost:8080/ws"); $scope.ws.onope ...

Is it possible to consolidate React and React-DOM into a unified library instead of having them separate?

Is it possible to combine React.JS and React-DOM.JS into a single library? In all the web applications I've encountered, we always have to import both libraries separately. Have there been any cases where either of these libraries can be used on its ...

Struggling with injecting $q into AngularJS?

Hey everyone! I've encountered a puzzling issue that I need help with. I'm attempting to inject the $q library into one of my controllers, but when I try to console.log() it, it shows up as "undefined". Oddly enough, I am successfully injecting ...

Tips for adjusting image and div sizes dynamically according to the window size

In my quest, the end goal is to craft a simplistic gallery that closely resembles this particular example: EXAMPLE: This sample gallery is created using Flash technology, but I aim to develop mine utilizing HTML, CSS & Javascript to ensure compatibil ...

What could be the reason for this XSS script not making a request to my server?

Currently diving into the realm of XSS attacks to enhance my knowledge on application security. My goal is to extract the user's cookie from a local website and then transmit it to my local server for testing purposes. I've successfully obtained ...

Unveiling the Power of KnockoutJS: Displaying HTML Content and Populating

I am trying to achieve a unique effect using KnockoutJS. Let's consider a basic model: var Item = function () { var self = this; self.title = ko.observable(""); }; In addition, I have a ViewModel: var ItemList = function () { var self = ...

Building a collapsible toggle feature with an SVG icon using HTML and CSS

I am trying to swap a FontAwesome Icon with a Google Materials SVG Icon when a collapsible table button toggle is pressed (changing from a down arrow to an up arrow). I have been struggling to get the Google Material Icons code to work. How can I resolve t ...

Why isn't v-model functioning properly in Vue?

In my current project involving an API, I encountered a problem. I utilized axios to fetch data from the API, which returned a JSON array. Each array item had a radio value that I appended to it. Despite attempting to use v-model to track changes in the ra ...

Tips for modifying JSON property names during the parsing process

As outlined in the JSON.parse documentation, a reviver function can be utilized to modify the value of each property within the JSON data. Here is an example: JSON.parse('{"FirstNum": 1, "SecondNum": 2, "ThirdNum": 3}', function(k, v) { return ...

Issue with passing parameter values in MVC Html.ActionLink

Currently, I am experimenting with MVC for a demonstration and have managed to put together some components. However, I am encountering difficulties with an Html.ActionLink. The goal is to display a series of dropdown lists to the user that must be selecte ...

Webpack returns an undefined error when attempting to add a JavaScript library

I am a newcomer to webpack and I am attempting to incorporate skrollr.js into my webpack setup so that I can use it as needed. However, I am unsure of the correct approach for this. After some research, I have found that I can either use an alias or export ...

Utilize the toString function along with the substring method within an ejs template

I am attempting to showcase an employee's ID by displaying only the last four digits in a table on an EJS page. The data is stored in MongoDB and I am using Express for handling routes. Here is my Express route: app.get('/routehere', async ...

changing pictures with jquery

Struggling with this code snippet: $('#clicked_package').css({"background-image" : "url(img/head_2.png)"}).fadeOut("slow"); $('#clicked_package').css({"background-image" : "url(img/head_2_normal.png)"}).fadeIn("slow"); No matter which ...