使用过滤器进行ng-repeat会产生不需要的$ index

时间:2017-06-13 01:37:09

标签: html angularjs

JS小提琴:http://jsfiddle.net/ernestsoo22/qqgj9jf5/1/

我的代码中有ng-repeat,如下所示:

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

有了这个,我能得到输出:

  

0,1,2,3

问题:使用这样的过滤器无法获得我想要的$index

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

使用此过滤器,我得到$index(参见小提琴):

  

0,1

而不是这个,我要找的是获取courses json对象的实际索引。所以根据过滤器,输出将是:

  

2,3

如何在使用filter时实现此目的?

2 个答案:

答案 0 :(得分:1)

使用ng-if="opt.code.indexOf('INF')>=0"中的li检查过滤器以检查INF现在

&#13;
&#13;
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"}];
}
&#13;
<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>
&#13;
&#13;
&#13;

答案 1 :(得分:0)

import React, { Component } from 'react';
import stateWrapper from 'react-state-helpers';

class App extends Component {
  render() {
    const { 
      mut, 
      values: { name } 
    } = this.props;

    return <InputComponent name={name} handleChange={mut('name')} />;
  }
}

export default stateWrapper(App)

这样可以解决吗?