Updating all values in a ng-repeat in AngularJS

I implemented a data model where the first ticker is initially set to selected by default.

Now, when a user clicks on another item, I want to efficiently deselect all other tickers and set the selected value to true for the clicked item:

<li class="ticker-li"
    ng-repeat="ticker in tickers"
    ng-hide="ticker.removed"
    ng-class="{'selected':ticker.selected}"
    ng-mouseleave="hideTickerOptions()">

    <div class="ticker"
         ng-click="unselectAll(); ticker.selected = !ticker.selected;
                   selectTicker(ticker);">
         {{ticker.ticker}}
    </div>
</li>

I attempted using a forEach function, but encountered an error stating that [object Array] is not a function:

var vs = $scope;

vs.unselectAll = function() {
   vs.tickers.forEach(vs.tickers, function(ticker) {
       ticker.selected = false;
   });
};

Although a regular for-loop solution can work, I am questioning its efficiency in toggling all the selected values to false:

for (var i = 0; i < vs.tickers.length; i++) {
    vs.tickers[i].selected = false;
}

My approach involves running the unselectAll function to clear selections before proceeding with selecting the current item in the markup:

<div class="ticker"
     ng-click="unselectAll(); ticker.selected = !ticker.selected;
               selectTicker(ticker);">
     {{ticker.ticker}}
</div>

Answer №1

I attempted to implement it using radio buttons.

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

app.controller('ctrlForm', function ($scope) {

        $scope.choices = [
            { id: 'Option1', selected: false },
            { id: 'Option2', selected: false },
            { id: 'Option3', selected: false },
            { id: 'Option4', selected: false },
            { id: 'Option5', selected: false },
            { id: 'Option6', selected: false },
            { id: 'Option7', selected: false }
        ];

        $scope.setDefaultSelection = function (selectedItem) {
            angular.forEach($scope.choices, function (choice) {
                choice.selected = false; // reset all selections
            });
            selectedItem.selected = true; // set the clicked one as selected
        };
        
    });
.highlighted {
        background-color: yellow;
    }
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.21/angular.min.js"></script>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script>

<div ng-app="FormApp" ng-controller="ctrlForm">
        <ul>
            <li style="list-style:none" ng-class="{'highlighted':item.selected}" ng-repeat="item in choices"><input type="radio" name="selection" ng-model="item.selected" ng-click="setDefaultSelection(item)" value="true" />{{item.id}}...{{item.selected}}</li>
        </ul>
    </div>

Answer №2

Utilizing a foreach loop would not be any less effective than what Angular can offer automatically. In either case, the selection of other items as unselected is necessary.

My suggestion would be to have a single "selectedItem" and a group of "items."

Then, you could do something like this:

<li class="ticker-li"
    ng-repeat="ticker in tickers"
    ng-hide="ticker.removed"
    ng-class="{'selected':ticker == selectedTicker}"
    ng-mouseleave="hideTickerOptions()">

    <div class="ticker" ng-click="selectedTicker = ticker">
         {{ticker.ticker}}
    </div>
</li>

Subsequently, you would be able to access the properties of the selectedTicker like so:

<div>{{selectedTicker.name}}</div>

Answer №3

If you are determined to use ticker.selected, you have the option of implementing a jQuery .each loop to deselect all of them.

$scope.selectTicker = function(ticker)
{
  //deselect all tickers
  $.each(tickers, function() { this.selected = false; });

  //select the ticker you passed in
  ticker.selected = true;
}

Furthermore, in your view:

<div class="ticker"ng-click="selectTicker(ticker);">
     {{ticker.ticker}}
</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

Assigning properties to the constructor using `this.prop`

Within a React class component, I have multiple methods and the component receives various props. I am contemplating whether I should assign each prop as this.propName in the constructor and then access them using this.propName. For your reference, below ...

What is the best way to incorporate raw HTML code into a .jsx file within a NextJS website?

I need to integrate Razorpay code into my NextJS website, but it's currently in pure HTML format. For example, the code looks like this: <form><script src="https://cdn.razorpay.com/static/widget/subscription-button.js" data-subscrip ...

Insert element into array // Angular leaflet

As a newcomer to Angular, I require assistance on how to insert an item into the markers.venues. This is my current code: var app = angular.module("basicMapApp", ["leaflet-directive"]); app.controller("CenterController", [ '$scope', functio ...

Utilizing React's createRef() for Enzyme testing

I am currently using the new React.createRef() api in one of my components. I am trying to figure out how to test if document.activeElement is equal to the current ref component. Here is the component code: export class Automatic extends Component { c ...

Retrieving an Angular Application directly from the Server

In order to ensure user authentication from the backend before any other code loads in my Angular app, I need the initial request sent to the backend to check if the user is authenticated. Only once the user has been verified as authenticated can the app b ...

The sluggishness of Ajax - A recursive problem

I've come across an issue with the ajax code I'm using to request a page. It's causing high memory consumption, slowing down the browser, and making everything lag. It seems like there's recursion happening but I'm not sure how to ...

What is the best way to include a class multiple times in a render method?

I'm currently working on a React project and have the following code snippet. <!DOCTYPE html> <html> <head> <meta charset="utf-8"> <meta name="viewport" content="width=device-width"> <title>JS Bin</t ...

Rectangles in collision: A mathematical analysis

After numerous attempts, I have developed a small "game" that incorporates collision detection. Unfortunately, I have encountered a persistent issue where objects sometimes pass through each other. The root cause of this problem eludes me completely. Ini ...

Receiving an abundance of alert notifications triggered by the search functionality of jsTree

I've created a function to search for text within the jsTree framework. The goal is to highlight the node if the search text is found. If not, inform the user with a message saying "No node matching the search string, please try again." However, I&a ...

Creating crawlable AMP versions of Angular websites

Having an Angular website where I dynamically load object properties, I am creating separate AMP sites for each of these objects. Typically, I would link to the AMP site from the canonical site. However, the issue arises because the crawler cannot find the ...

Incorporate new content into an element within a JavaScript array

I need help with the following code: let options = new Array("text1","text2"); I am trying to add additional text to each element in the array, so it becomes Array("text1 someothertext","text2 sometext"); Your assistance is greatly appreciated. ...

Enhancing PHP function speed through pre-compilation with Ajax

I am curious about compiling server side functions in PHP with Ajax, specifically when multiple asynchronous calls are made to the same server side script. Let's consider a PHP script called "msg.php": <?php function msg(){ $list1 = "hello world ...

Issue with displaying Bootstrap modal form upon clicking the button

Currently, I am working on a website using bootstrap, firebase, and JQuery. The main functionality involves displaying a modal when a button is clicked so that users can input data. This data is then saved in the Firebase database and displayed on a table ...

How can I dynamically redirect based on the selected radio button value in a React application?

I've been attempting to use the "navigate" method from "react-router-dom" to redirect users from the Login screen based on the radio button they click. I've tried using states, but I'm unsure if that's the best approach or if there&apos ...

Clearing form data after submitting in Laravel using axiosIn Laravel, utilizing

When working on my Laravel app, I encountered an issue while submitting a form using Vue and Axios. Despite my attempts to clear the input field after submission, it doesn't seem to work. HTML: <form method="post" enctype="multipart/form-data" v- ...

What is the best way to sequentially call multiple API endpoints using React, Redux, and JavaScript?

I am facing a challenge with my Redux store, as it contains multiple states that are populated by the same API but from various endpoints. Within my React app, I have several components that need access to one of these states. They all make calls to the c ...

What is the method for modifying the background color of the inner circle in a highchart doughnut chart?

Trying to Modify the Background Color of a Highchart Doughnut Desired Outcome https://i.sstatic.net/Fk9oS.png Current Outcome https://i.sstatic.net/CTZqZ.png JS Fiddle Link : https://jsfiddle.net/shantanugade/f5ojh13z/1/ Seeking assistance with this is ...

Firestore behaving inconsistently by returning an empty promise even when data is available

I am working on an asynchronous function that retrieves tokens for a list of user ids. This function queries firestore to get the token associated with each user id within the list. async function fetchUserTokens(ids) { const promises = ids.map(async (id ...

What is the reason behind AngularJS consistently selecting the first TD cell?

I'm a beginner in AngularJS and I'm testing my skills by creating a small game. Here's the table structure I have: <table class="board"> <h1>Table</h1> <input type="number" ng-model="val"><button ng-click="ctrl.f ...

The input box refuses to accept any typed characters

I encountered a strange issue where the input box in the HTML was not allowing me to type anything. const para = document.createElement('p') const innerCard = document.getElementsByClassName('attach') for(let i = 0; i < innerCard.l ...