Ernest Soo Ernest Soo -4 years ago 43
AngularJS Question

ng-repeat with filter yields unwanted $index

JS fiddle: http://jsfiddle.net/ernestsoo22/qqgj9jf5/1/

I have a

ng-repeat
in my code like this:

<ul>
<li ng-repeat=" opt in courses">
{{$index}}
</li>
</ul>


With this, I am able to get the output of:


0 , 1 , 2 , 3


Problem: Using a filter like such does not get the
$index
that I want:

<ul>
<li ng-repeat=" opt in courses | filter:{code:'INF'}" >
{{$index}}
</li>
</ul>


With this filter I get the
$index
of (refer fiddle):


0 , 1


Instead of this, what I am looking for is to get the actual index of the
courses
json object. So according to the filter, the output would be:


2 , 3


How can I achieve this while using a
filter
?

Answer Source

Use ng-if="opt.code.indexOf('INF')>=0" in li to check the filter to check the INF present

function TodoCtrl($scope) {
 $scope.courses = [
    {"code":"ICT10001","description":"Problem Solving with ICT","credits":"12.5","type":"Core"},
    {"code":"COS10005","description":"Web Development","credits":"12.5","type":"Core"},
    {"code":"INF10003","description":"Introduction to Business Information Systems","credits":"12.5","type":"Core"},
    {"code":"INF10002","description":"Database Analysis and Design","credits":"12.5","type":"Core"}];
}
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>
<div ng-app>
  <div ng-controller="TodoCtrl">
<ul>
    <li ng-repeat=" opt in courses" ng-if="opt.code.indexOf('INF')>=0"   >
    {{$index}}
    </li>
    </ul>
  </div>
</div>

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