Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

$first in ngRepeat

I have an array $scope.items.

I want if the item is the $first one of the ngRepeat to add the css class in.

Is it something that can be done with angular? Generally how can I handle the booleans in Ajs?

<div ng-repeat="item in items">    <div class='' > {{item.title}}</div> </div> 
like image 446
Diolor Avatar asked Oct 28 '13 13:10

Diolor


People also ask

How do I get an index value in ng-repeat?

Note: The $index variable is used to get the Index of the Row created by ng-repeat directive. Each row of the HTML Table consists of a Button which has been assigned ng-click directive. The $index variable is passed as parameter to the GetRowIndex function.

What is ngRepeat?

AngularJS ng-repeat Directive The ng-repeat directive repeats a set of HTML, a given number of times. The set of HTML will be repeated once per item in a collection. The collection must be an array or an object. Note: Each instance of the repetition is given its own scope, which consist of the current item.

What is track by in AngularJS?

"track by" tells the angular js that how angular js will track the association between DOM and the model (i.e. collection). Internally angular js uses "track by $id(obj)" for this purpose. You can use track by $index if you do not have a unique identifier.

How do you use NG bind?

Definition and UsageThe ng-bind directive tells AngularJS to replace the content of an HTML element with the value of a given variable, or expression. If the value of the given variable, or expression, changes, the content of the specified HTML element will be changed as well.


2 Answers

It should be

<div ng-repeat="item in items">    <div ng-class='{in:$first}' > {{item.title}}</div> </div> 

Look at ng-class directive in http://docs.angularjs.org/api/ng.directive:ngClass and in this thread What is the best way to conditionally apply a class?

like image 100
Chandermani Avatar answered Sep 29 '22 22:09

Chandermani


You can try approach with method invocation.

HTML

<div ng-controller = "fessCntrl">  <div ng-repeat="item in items">    <div ng-class='rowClass(item, $index)' > {{item.title}}</div>    </div> </div> 

JS

var fessmodule = angular.module('myModule', []);  fessmodule.controller('fessCntrl', function ($scope) {    $scope.items = [        {title: 'myTitle1', value: 'value1'},        {title: 'myTitle2', value: 'value2'},        {title: 'myTitle3', value: 'value1'},        {title: 'myTitle4', value: 'value2'},        {title: 'myTitle5', value: 'value1'}    ];               $scope.rowClass = function(item, index){          if(index == 0){              return item.value;          }         return '';     };         });     fessmodule.$inject = ['$scope']; 

Demo Fiddle

like image 26
Maxim Shoustin Avatar answered Sep 29 '22 23:09

Maxim Shoustin