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

Tips on incorporating JavaScript files into Angular applications

Struggling to incorporate a JavaScript function into Angular, I have installed the plugin "npm I global payments-3ds". I copied the JavaScript files from node_modules and attempted to call them in my component. Below is an example: import { ...

The Angular @Input directive may be prone to receiving inaccurate model data

I am currently working on setting up @Input for my component using a model that resembles the following: interface Car { sail?: never tires: number weight: number } interface Boat { tires?: never sail: boolean weight: number } exp ...

Passing a function from one directive to another directive

I am facing a situation where I have two directives that are separate. If a certain condition is evaluated as true, I need to call the second directive from within the first one. myDirectives.directive('first', function() { return { restri ...

The Element Datepicker incorrectly displays "yesterday" as an active option instead of disabled when the timezone is set to +14

After adjusting my timezone to +14 using a chrome plugin, I noticed that the calendar app is displaying incorrect disabled dates. You can view the issue here. This is the formula I'm currently utilizing to disable dates: disabledDate(time) { re ...

The autofocus feature on the textarea in Angular Material Dialog seems to be malfunctioning

Within a web app, I am utilizing the Dialog component from Angular Material. The Dialog consists of only a textarea that is initially empty. I aim to automatically focus on the textarea when the user opens the modal dialog. How can I achieve this? Despite ...

Changing states in Ionic Nav View triggers a controller change, however, the view remains the same

Having some trouble with routing in Ionic and Ui-Router. I'm noticing that when I click on the link to change the view (using an anchor tag with ui-sref), the controller changes as expected (I can see output in the console), but the view remains uncha ...

Utilizing Regular Expressions in JavaScript to extract packages from an Android manifest document

When it comes to Android APK files, the manifest files play a crucial role: <?xml version="1.0" encoding="utf-8"?> <manifest xmlns:android="http://schemas.android.com/apk/res/android" package="com.example.myapp" android:versionCode="1" ...

How can you set a $_GET variable without having to reload the page?

I have a table on my website that displays values for each row, and here's an example code snippet: //JAVASCRIPT <tr onclick="window.history.replaceState(null, null, 'myPage.php?ID=2');"> The URL changes with this code, but it doesn& ...

How should a successful post request be properly redirected in React?

I am in the process of learning React and currently working on a small project. I have set up a NodeJS server to handle my requests, and now I am facing an issue with redirecting the user after a successful login. I successfully dispatch an action and upda ...

The ng-controller is not functioning properly even when being correctly invoked

I tried out some simple angularjs code, utilizing nodejs, angularjs, and html. Here are my files: https://github.com/internial/test. I decided not to include the node_modules folder as it was too large. On localhost:8080, this is the result: {{1 + 64}} ...

What is the best way to pass a VueJS object to be stored in a Laravel controller?

I am facing an issue with my methods where the data is not getting stored in the database. I am unsure why the information is not being sent to the controller. Even though I input the correct data, it fails to load into the database. However, it does pass ...

Having trouble reading the file using jQuery in Internet Explorer 8 and earlier versions due to its non-XML format (albeit resembling XML)

Currently, I am utilizing AJAX to load a KML file (which essentially functions as an XML file). The parsing works seamlessly in IE9, FF, and other browsers, but encounters issues in IE8. Although the data is retrieved, I face difficulties parsing it in jQu ...

What is the correct way to execute a jQuery trigger on a checkbox or radio button to simulate a user clicking on it?

My current page utilizes can.js, making it challenging to replicate the issue on jsfiddle.net. The result I am experiencing is as follows: When I click on a checkbox (or even a radio button), an input text box should update accordingly (for example, displ ...

The local server for handling HTTP requests has ceased to operate

Recently, I set up the NPM package along with the http server within the "server" directory. Initially, everything was functioning smoothly; however, the server abruptly ceased operating. Upon attempting to launch the local http server, an error message a ...

How to pass data/props to a dynamic page in NextJS?

Currently, I am facing a challenge in my NextJS project where I am struggling to pass data into dynamically generated pages. In this application, I fetch data from an Amazon S3 bucket and then map it. The fetching process works flawlessly, generating a se ...

Guide for setting up a React infinite scroll feature in a messaging app similar to Facebook Messenger

I have been exploring various questions regarding React infinite scroll, but I am looking to delve deeper in order to discover the most effective solution available for implementing such a component. Currently, I am working on a chat application and have ...

Winston prefers JSON over nicely formatted strings for its output

I have implemented a basic Winston logger within my application using the following code snippet: function Logger(success, msg) { let now = new Date().toUTCString(); let logger = new (winston.Logger)({ transports: [ new (winsto ...

Having trouble retrieving the table value from an HTML document?

I am trying to retrieve specific information from this source: This information is crucial for fetching data from a database using a primary key. However, extracting this value has proven to be quite challenging. Upon document readiness, I execute the fol ...

Navigating through the DOM using JavaScript or regular expressions

I have a DOM string called innerHTML and I am looking to extract or display the node value using either JavaScript's DOM API or JavaScript RegEx. "<nobr> <label class="datatable-header-sortable-child" onmousedown="javascript:giveFeedback(&ap ...

"Customize the appearance of a List Element in Material UI by changing

How can I modify the color of a specific material ui list item? <ListItemText primary={mspvar} secondary="buy"> ...