Best Method for Updating a Single Scope and Setting the Others to False in AngularJS

If I have 4 fields in my view that need to be toggled open or closed when clicked, with the requirement of closing the other three, how can this be achieved without duplicate code?

<div class="square red"></div>
<div class="square blue"></div>
<div class="square yellow"></div>
<div class="square green"></div>

To achieve this, I added an ng-class triggered by a ng-click for each field. Here's an example:

<div class="square red" ng-class="{'open':redSquare == true}" ng-click="clickRedSquare()"></div>
<div class="square blue" ng-class="{'open':blueSquare == true}" ng-click="clickBlueSquare()"></div>
<div class="square yellow" ng-class="{'open':yellowSquare == true}" ng-click="clickYellowSquare()"></div>
<div class="square green" ng-class="{'open':greenSquare == true}" ng-click="clickGreenSquare()"></div>

In the controller, the logic is implemented as follows:

$scope.redSquare = true;
$scope.clickRedSquare = function() {
    $scope.redSquare = !$scope.redSquare;
    $scope.blueSquare = false;
    $scope.greenSquare = false;
    $scope.yellowSquare = false;
};
// Repeat for other colors...

Is there a more optimal way in Angular to prevent duplicate code? You can check out the working plunkr here. Thank you!

Answer №1

In order to maintain separate variables for each square, you can implement the following solution:

$scope.clickSquare = function(name) {
    ["redSquare",
     "blueSquare",
     "greenSquare",
     "yellowSquare"].forEach(function(square) {
        $scope[square] = (square === name) ? !$scope[square] : false;
     });
}

Simply invoke this method with an argument like

ng-click="clickSquare('redSquare')"

Check out the updated Plunker

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

Is there a way to extract data from a JSON file with dc.js?

As a beginner in programming, I am looking to learn how to import data from a JSON file using dc.js. ...

Unexpected value assigned to private variable within a PHP class

Initially, the issue I am encountering originates from my PHP class that is called by a PHP file accessed through an AJAX call. The main problem lies in the fact that the return value does not align with the sybase_result value. What could possibly be mis ...

Tips for testing a function within an AngularJS service using simulated data

Looking to write a Jasmine unit test for a specific function within an AngularJS service provider called shapesResolver. The goal is to create mock data for myObject and then test the function getObjectShape() using that mock data as a parameter. How can ...

Guide to updating current rjs files to incorporate jQuery and json in Rails 3

Currently, in my Rails 3 application, I am using rjs to render partials in my controllers. An example of this is when saving a new item to a table, the table gets refreshed: respond_to do |format| format.js { render :update do |page| ...

How can I extract several values from a child component in React?

Is there a way to retrieve two values in a single method of the Parent Component by passing props value from Child Component? What would be the best approach? Form.js (Child Component) // First method -> Extracting the suggestion value and passing i ...

Creating a Query String in a web URL address using the state go method in Angular State Router

On my product list page, there is a list of products. When I click on a particular product, a function is called that uses state.go. Issue with dynamic functionality: $state.go('home.product.detail', { 'productID': "redminote4", &apo ...

Having trouble getting unique input values to pass through ajax

For the past couple of weeks, I've been searching for a solution to my issue. The problem arises in my PHP foreach loop where I have div tags representing rows of data fetched from the database. Each div row contains HTML input elements and a button t ...

Transmitting a custom PDF document through email with React and Node.js

Currently, I am in the process of developing an application designed to streamline the completion of a complex form. The data entered into this form will be stored on a remote database for future reference and editing purposes. Once the form is ready for s ...

Transform a protractor screenshot into a PDF file

I'm currently working on a small Protractor code that captures screenshots, but my goal is to save these screenshots as PDF files. Below you can find the code snippet I have written. await browser.get(url); const img = await browser.takeScreenshot(); ...

Accessing data stored in XML or JSON files from a local server

I am currently working on loading a list of coordinates for a Google map from either an XML or JSON file, both of which are hosted in the same directory on my local test server. So far, I have used a hard-coded JSON object to load map coordinates for tes ...

What is the best way to align my clip-path's text with the center of the viewport and ensure that all of the clip-path's text is visible?

Check out my React component demo: https://codesandbox.io/s/epic-brown-osiq1. I am currently utilizing the values of viewBox, getBBox, and getBoundingClientRect() to perform calculations for positioning elements. At the moment, I have hardcoded some values ...

Utilizing AngularJS to showcase and verify a form field populated by JSON data

I am looking to set up a form with validation and a submit button. As a beginner in Angular, I'm not entirely sure where to start. - I need some guidance on what Controller to use or perhaps a starting point. JS: myApp.controller('jsonCtrl&a ...

Store picture documents in web software program, java

I have a web application where I need to allow "client side users" to upload a large number of image files, and "customer side users" should be able to view a grid layout of the uploaded images. All image files should be accessible for uploading, viewing, ...

Copying Objects in JavaScript Using Deep Cloning

My current project involves using Nodejs to create a deep copy of an object generated by Squel, a query building library. The main dilemma lies in how to replicate the exact filteredQuery variable. The object is initialized with: filteredQuery = squel.sel ...

Including an anchor element with a specified URL, alongside passing the URL as a property

Having trouble passing a URL to href using a property. I'm attempting to pass the {props.github} value to href, but it's not working as expected. I've set up a property object with a field called github like this: export const projectList ...

Only initiate the loading of the iframe within the div upon clicking a specific element

Is there a way to delay loading the content of a div until it's clicked, instead of having all data loaded at once when the page loads? I noticed that removing unnecessary divs made the page load much faster. How can I prevent all data from being loa ...

The body classList variable is inaccurately updated when making a JQuery Ajax call

Currently, I am in the process of developing a script to manage Ajax page transitions using JQuery's Ajax request function. Within the success callback of the Ajax function, it is essential for me to access the classList of the current page's bod ...

Experiencing difficulties with retrieving form data in req.body using Express and node.js

I am facing an issue while trying to create a registration form for new users with profile picture upload. Despite adding body-parser middleware, the form data is not passing correctly to the route and I cannot identify the reason behind it. Error: D:&bso ...

Tips for customizing the border of an outlined TextField in MUI

Below is the current configuration of a TextField component: const styles = { resize: { fontSize: '50px', } } const textField = (props) => { const { classes } = props; return ( <TextField valu ...

Embracing JQuery for Frontend Development with Node.js

I'm currently enhancing my node.js skills by utilizing express, and I've encountered a situation that is causing me some confusion. Essentially, when a user requests a webpage and the backend sends them the HTML page, how can I incorporate a Java ...