Search code examples
javascriptarraysangularjsng-class

Array of objects set to 'active' in Angular


I have a listing of items utilizing ng-repeat

Object

var items = [{"name": "item1"},
 {"name": "item2"}...
];

HTML

<div ng-repeat="item in items" ng-click="addItemToCollection(item)">
  {{item.stuff}}
</div>

addItemToCollection simply takes which one was selected and adds or splices it into a different array with some logic applied to either allow it or deny it so I end up with something like:

var selectedItems = [{"name": "item15"},
 {"name": "item26"}...
];

How would I bind this new array to an active class on the original array, that is if item3 and item5 were clicked, set a class of 'active' on both of them?

ie:

{{item1.stuff}}
{{item2.stuff}}
{{item3.stuff}} // (has class active based on 2nd array)
{{item4.stuff}}
{{item5.stuff}} // (has class active based on 2nd array)

where:

selectedItems = [{"name": "item3"},
 {"name": "item5"}...
];

What would be the best way to set up an ng-class on my ng-repeat declaration to reflect this?


Solution

  • I think the easiest way to just add a class for each addition to the selectedItems array is to user to following code:

    <!-- toggle class with active field -->
    <li class="list-group-item"
      ng-repeat="item in items"
      ng-class="{'active': active}"
      ng-click="active = toggleSelect(item)"> <!-- set active field on select -->
      {{ item }}
    </li>
    

    As you can see I've used a toggleSelect function which returns bool depending on toggle status (addition or removal of item). Implementation:

    $rootScope.toggleSelect = function(item) {
        var itemIndex = false;
    
        //find item index if existing in selectedItems array
        for(var i = 0; i < $rootScope.selectedItems.length; i++) {
          if($rootScope.selectedItems[i].name === item.name) {
            itemIndex = i;
          }
        }
    
        //Add to array if not exists
        if(itemIndex === false) {
          $rootScope.selectedItems.push(item);
        }
        //Remove if item exists
        else {
          $rootScope.selectedItems.splice(itemIndex, 1);
        }
    
        //Return toggle status (item addition or removal)
        return (itemIndex === false);
    };
    

    JS Bin example