$index inside ng-repeat with ng-if
angularjs
Solution
Instead of using ng-if, I would use a filter. then, the $index will be always correspond to the index in the result list after applying the filter
<div data-ng-repeat="item in items|filterFruit">
<label ng-style="setBGColor($index)">{{item.name}}</label>
</div>
angular.module('app.filters', []).filter('filterFruit', [function () {
return function (fruits) {
var i;
var tempfruits = [];
var thefruit;
if (angular.isDefined(fruits) &&
fruits.length > 0) {
for(thefruit = fruits[i=0]; i<fruits.length; thefruit=fruits[++i]) {
if(thefruit.type =='fruit')
tempfruits.push(thefruit);
}
}
return tempfruits;
};
}]);
Problem
I Have an array of items like this which contains a list of animals and a list of fruits in a random order. ``` $scope.items = [{name:'mango',type:'fruit'},{name:'cat',type:'animal'},{name:'dog',type:'animal'},{name:'monkey',type:'animal'},{name:'orange',type:'fruit'},{name:'banana',type:'fruit'},...] ``` Then I Have a array of colors like ``` $scope.colorSeries = ['#3366cc', '#dc3912', '#ff9900',...]; $scope.setBGColor = function (index) { return { background: $scope.colorSeries[index] } } ``` I am using the items array to render the fruits only in a div with background color selected from the colorSeries based on the index like colorSeries[0] which will give me #3366cc ``` <div data-ng-repeat="item in items " ng-if="item.type =='fruit'"> <label ng-style="setBGColor($index)">{{item.name}}</label> </div> ``` Things working fine if the length of the items array is less than length of `colorSeries` array.The problem arises if the length of `colorSeries` array is less than the items array.e.g if i have a color series with 3 colors then for this items array the last item i.e orange will need a color indexed as `colorSeries[4]` which is `undefined` where as I have rendered only three items. So, is it possible to get the index like 0,1,2 i.e the index of elements rendered with `ng-if`.