Saurabh Pakhare Saurabh Pakhare - 2 months ago 23
AngularJS Question

Change the style of particular elements of an array inside ng-repeat in AngularJs

E.g
I have an array of text like

$scope.array = [{text:'abc'}, {text:'pqr'}, {text:'xyz'}];

Now along with
ng-repeat
I want to change the colour of the text of any particular element of the array. how to achieve it?

Answer

IMO, we've multiple options to achieve that.

If you want to change single property then you can use ng-style but let say if you want to manipulate multiple properties then its preferable to use ng-class.

ng-style

The ngStyle directive allows you to set CSS style on an HTML element conditionally.

<div ng-repeat="contact in jsonContacts">
    <span ng-style="{'color':($first ?'red':'blue')}">{{data.row}}</span>
</div>

ng-class

The ngClass directive allows you to dynamically set CSS classes on an HTML element by databinding an expression that represents all classes to be added.

<div ng-repeat="i in array" ng-class="{'green': $last, 'blue': $first}">
    {{i.text}}
</div>

FYI,

The ngRepeat directive instantiates a template once per item from a collection. Each template instance gets its own scope, where the given loop variable is set to the current collection item, and $index is set to the item index or key.

$first boolean true if the repeated element is first in the iterator.

$middle boolean true if the repeated element is between the first and last in the iterator.

$last boolean true if the repeated element is last in the iterator.

Official documentations

ngRepeat

ngClass

ngStyle

Hope this helps you :)

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

app.controller('homeCtrl', function($scope) {
  $scope.array = [{text:'abc'}, {text:'pqr'}, {text:'xyz'}];
});
.green
{
  color: green;
}
.blue
{
  color: blue;
}
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>

<div ng-app="app">
  <div ng-controller="homeCtrl">
    <h3>ng-style used</h3>
    
    <div ng-repeat="i in array" ng-style="{'color':($first ?'red':'blue')}">{{i.text}}</div>
    
    <br/>
    <h3>ng-class used</h3>
  <div ng-repeat="i in array" ng-class="{'green': $last, 'blue': $first}">{{i.text}}</div>
  </div>
  
  </div>
</div>