Isetty Ravitejakumar Isetty Ravitejakumar - 3 months ago 188
AngularJS Question

How to make md-list-item active when selected during ng-repeat?

Here is my scenario

When i select any one item in list(

<md-list-item>
) an active class should be appended for the particular item.

When iam trying to do it, active class getting appended for all the items. Please help me if anyone knows the solution. Iam new to material design.

<md-list-item class="md-3-line" ng-repeat="review in oReviews" ng-click="fnReviewEmployeeId(review.empId)">
<img ng-src="https://x1.xingassets.com/assets/frontend_minified/img/users/nobody_m.original.jpg" class="md-avatar">
<div class="md-list-item-text" layout="column">
<h3>
{{review.name }}
</h3>
<span class="review-subtext">{{review.info}}</span >
<p class="review-status">{{review.status}}</p>
</div>
<md-divider></md-divider>
</md-list-item>

Answer

Here's one way of doing it - CodePen

Markup

<div ng-controller="AppCtrl" ng-cloak="" ng-app="MyApp">
  <md-list>
    <md-list-item class="md-3-line" ng-repeat="review in oReviews" ng-click="fnReviewEmployeeId($index)" ng-class="{selectedIndex: selectedIndex===$index}">
      <img ng-src="https://x1.xingassets.com/assets/frontend_minified/img/users/nobody_m.original.jpg" class="md-avatar">
      <div class="md-list-item-text" layout="column">
        <h3>
          {{review.name }}
        </h3>
        <span class="review-subtext">{{review.info}}</span >
        <p class="review-status">{{review.status}}</p>
      </div>
      <md-divider></md-divider>
    </md-list-item>
  </md-list>
</div>

JS

angular.module('MyApp',['ngMaterial', 'ngMessages', 'material.svgAssetsCache', 'ngDialog'])

.controller('AppCtrl', function($scope) {
  $scope.selectedIndex = null;
  $scope.oReviews = [
    {name: "Cheese", info: "Dairy", status: "Delicious"},
    {name: "Beef", info: "Cow", status: "Versatile"},
    {name: "Bread", info: "Yeast", status: "Everywhere"},
  ];

  $scope.fnReviewEmployeeId = function (index) {
    if ($scope.selectedIndex === null) {
      $scope.selectedIndex = index;
    }
    else if ($scope.selectedIndex === index) {
      $scope.selectedIndex = null;
    }
    else {
      $scope.selectedIndex = index;
    }
  }
});

CSS

.selectedIndex {
  background: yellow;
}