Saurabh Pakhare Saurabh Pakhare - 1 year ago 99
AngularJS Question

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

I have an array of text like

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

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

Answer Source

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.


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>


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}">


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




Hope this helps you :)

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

app.controller('homeCtrl', function($scope) {
  $scope.array = [{text:'abc'}, {text:'pqr'}, {text:'xyz'}];
  color: green;
  color: blue;
<script src=""></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>
    <h3>ng-class used</h3>
  <div ng-repeat="i in array" ng-class="{'green': $last, 'blue': $first}">{{i.text}}</div>

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download