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

JavaScript method overloading involves defining multiple functions with the same name

In my JavaScript code, I have implemented method overloading using the following approach: function somefunction() { //1st function } function somefunction(a) { //2nd function } function somefunction(a,b) { //3rd function } somefunction(); // ...

Displaying data stored in a database using JSON format with Ember

I seem to be facing a challenge once again. Let me elaborate on what I am trying to achieve. Within the teammembers template, I aim to display information about Team Members and their details from a specific team by joining 3 tables. Here is an example o ...

Personalizing the dimensions of audio.js

I recently integrated the audio.js plugin into my website. I've added the necessary code to the header.php file located in the includes folder. <script src="audio/audiojs/audio.min.js"></script> While the player appears correctly on othe ...

Can a synchronous loop be executed using Promises in any way?

I have a basic loop with a function that returns a Promise. Here's what it looks like: for (let i = 0; i < categories.length; i++) { parseCategory(categories[i]).then(function() { // now move on to the next category }) } Is there ...

Obtaining connection data in jsPlumb can be accomplished through a variety of

I have created a compact table of nodes that allow me to drag and drop connections or manually input node IDs to establish connections between them. Despite searching through the documentation and scouring the internet for examples, I am struggling to fin ...

Is the jqm flipswitch with the label on the left and the switch on the right?

My goal is to display multiple flipswitches on a mobile app page. This is the code I am using: <div class="ui-content"> <form> <fieldset> <div data-role="fieldcontain"> <label for="checkbox-based-flipswitch" ...

Encountering challenges with managing global variables in my Node.js application

I am facing a problem with global variables in my NodeJs application. The project involves webservices created using the express module. When a client accesses the service, a json object is sent in the request body. I extract all properties from the reques ...

Purge stored events from BehaviorSubject in Angular2 using Observables as they are consumed

I'm encountering an issue that I believe stems from my limited understanding of Observables. This project is built on Angular2 (v4.0.3) and employs rx/js along with Observables. Within a state service, there exists a store for events: // Observab ...

Can you please explain the purpose of the state object in the setSearchParams hook of react-router-dom v6

Can anyone explain the { state: ? } parameter used in the update function of useSearchParams? const [search, setSearch] = useSearchParams(); setSearch( { ...Object.fromEntries(search), transFilters: JSON.stringify(filters), }, { ...

Passing image source from parent component to child component in Vue.js

I encountered an issue where I stored the image file name in a variable within the parent component and passed it to the child component using props. However, despite this setup, the child element is not displaying the image as expected. Here is the data ...

Managing both clicking and hovering events on a single element, ensuring that the popup modal remains open as long as it is being hovered over

After successfully implementing click and hover functionality on an element, I was able to position the popup relative to the mouse pointer based on a previous solution. However, I am now facing an issue where I want the popup modal to be fixed in a specif ...

How to mock nested functions within sinon

There are several questions similar to this one, but none of them quite match the scenario I'm dealing with. The situation involves a function that takes another function as a parameter: var myfunc = (func_outer) => { return func_outer().func ...

What are the consequences of excluding a callback in ReactJs that may lead to dysfunctionality?

<button onClick = { () => this.restart()}>Restart</button> While going through a ReactJs tutorial, I encountered a game page which featured a restart button with the code snippet mentioned above. However, when I tried to replace it with the ...

Continue iterating only when all promises have been resolved

My AngularJS requirement involves the following: for (var i = 0, len = self.Scope.data.length; i < len; i++) { var data = self.Scope.data[i]; var self = this; //Executing First asynchronous function self.EcritureService.createNewDa ...

The issue with the functionality of position absolute in CSS when used with JavaScript

<html> <head> <style> #wrapper{ position: absolute; top : 250px; width: 500px; height: 500px; border: 1px solid red; } .tagging{ position: absolute; border: 1px solid black; width : 20px; height: 30px; } & ...

An easy way to switch animations using CSS display:none

Dealing with some missing gaps here, hoping to connect the dots and figure this out. I'm attempting to create a functionality where a div slides in and out of view each time a button is clicked. Eventually, I want multiple divs to slide out simultane ...

Using HTML5 Canvas with Firefox 4: How to Retrieve Click Coordinates

Lately, I've been diving into creating HTML5 Video and Canvas demos. Initially, my focus was on optimizing them for Chrome, but now I'm shifting my attention to Firefox and Safari as well. One particular demo I'm currently working on involv ...

Troubleshooting Problem with Materializecss Datepicker Displaying Dates

Utilizing Materializecss' datepicker feature within a form, I encountered an issue where the input format changes when the user interacts with it: https://i.sstatic.net/E4zKR.png To achieve this formatting using Angular, my code snippet was as follo ...

Ways to showcase a website within an HTML document using a URL?

Is it possible to show 2 webpages on a single aspx webpage? For instance, When a user opens the link for www.mywebsite.com, I would like to display both www.google.com and www.bing.com on my homepage. Behind the scenes, I will call two separate URLs an ...

javascript The unchecking of a checkbox is not functioning

I am facing an issue with this JavaScript code. The problem is that when I uncheck a value, it removes all the values from the result instead of removing just the specific unchecked value. Can someone please help me with this? <script> window.addE ...