krsna
krsna

Reputation: 4333

How to apply style for each md-chip which are looped in ng-repeat: AngularJS

I'm trying to apply style to chips only when the chips are clicked. I want user to know which chips are selected.

Problem with my approach is, with the ng-repeat, all the chips are getting styled even when one chip is clicked. How do I apply style only for the chip which user selects and remove the styling when user clicks the same chip again just like toggling / as in checkboxes.

Here's the excerpt from my code:

HTML Code

<div layout="row">
  <md-chips ng-repeat="filter in filters" readOnly="true">
    <md-chip ng-style="{'background': isActive ? 'green' : '' }" 
             class="chipStyling" ng-click="setActiveFilter(filter,$index)">
      {{filter.name}}
    </md-chip>
  </md-chips>
</div>

JS Code

angular.module('BlankApp', ['ngMaterial', 'ngMessages'])

.controller('ctrl', function($scope){
  $scope.isActive = false;
  $scope.filters = [
    {name: 'Google', type: 'sm'},
    {name: 'Facebook', type: 'sm'},
    {name: 'Twitter', type: 'sm'}
  ]

  $scope.setActiveFilter = function (filter, index) {
        $scope.isActive = true;
        console.log('Active filter - ' + $scope.isActive + " ; index - " + index);
    }
});

I created a Code Pen Could anyone please review and let me know where I'm doing it wrong.

Upvotes: 2

Views: 176

Answers (2)

Mohrn
Mohrn

Reputation: 816

You need to keep the state for each chip. Updated code pen

angular
  .module("BlankApp", ["ngMaterial", "ngMessages"])
  .controller("ctrl", function($scope) {
    $scope.filters = [
      { name: "Google", code: "g", isActive: false },
      { name: "Facebook", code: "f", isActive: false },
      { name: "Twitter", code: "t", isActive: false }
    ];

    $scope.toggleActiveFilter = function(filter) {
      filter.isActive = !filter.isActive;
      console.log(
        `Active filters: ${$scope.filters
          .filter(({ isActive }) => isActive)
          .map(({ name }) => name)
          .join(", ")}`
      );
    };
  });

I also took the liberty to change so it's toggling instead of just setting to true.

Upvotes: 1

georgeawg
georgeawg

Reputation: 48948

Make the isActive variable a property of each filter object:

<div layout="row">
  <md-chips ng-repeat="filter in filters" readOnly="true">
    <md-chip ng-style="{'background': filter.isActive ? 'green' : '' }" 
             class="chipStyling" ng-click="setActiveFilter(filter,$index)">
      {{filter.name}}
    </md-chip>
  </md-chips>
</div>

Then set that property:

$scope.setActiveFilter = function (filter, index) {
    filter.isActive = true;
}

Upvotes: 1

Related Questions