Leon Gaban Leon Gaban - 1 year ago 69
AngularJS Question

AngularJS : How to change a value in all items in an ng-repeat

I have a data model that comes in, by default I give the first ticker a selected status of true.

Now when a user clicks another item, I need to efficiently deselect all the others and set the selected value to true for the item clicked:

<li class="ticker-li"
ng-repeat="ticker in tickers"

<div class="ticker"
ng-click="unselectAll(); ticker.selected = !ticker.selected;

Tried a
function here, but with the error
[object Array] is not a function

var vs = $scope;

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

A regular for-loop will work, but is it an efficient way to toggle all the selected values to false?

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

My thinking here is run this unselectAll function to deselect everything, then the next code in the markup which select the current item:

<div class="ticker"
ng-click="unselectAll(); ticker.selected = !ticker.selected;

Answer Source

I tried to do it using radio inputs.

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

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

        $scope.choices = [
            { id: 'Choice1', check: false },
            { id: 'Choice2', check: false },
            { id: 'Choice3', check: false },
            { id: 'Choice4', check: false },
            { id: 'Choice5', check: false },
            { id: 'Choice6', check: false },
            { id: 'Choice7', check: false }

        $scope.setDefault = function (item) {
            angular.forEach($scope.choices, function (p) {
                p.check = false; //set them all to false
            item.check = true; //set the clicked one to true
.selected {
        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="AppForm" ng-controller="ctrForm">
            <li style="list-style:none" ng-class="{'selected':item.check}" ng-repeat="item in choices"><input type="radio" name="group" ng-model="item.check" ng-click="setDefault(item)" value="true" />{{item.id}}...{{item.check}}</li>