angularjs过滤器来比较字符串中的单词

时间:2016-06-06 11:06:40

标签: angularjs filter

如果用户选择busTye为“A / C”,那么我想从JSON过滤A / C总线:

Index.html:

  <div class="col-md-3">
    <label for="type">Bus Type</label>
    <select name="busType" id="busType" ng-model="type">
    <option>A/C</option>
    <option>Non A/C</option>
    <option>Sleeper</option>
    <option>Semi Sleeper</option>
    <option>pushback</option>
    <option>MultiAxle</option>
    </select>   
 </div>

  <table ng-repeat="j in busDetails | filter: type:j.busType">
  <td>{{j.operatorName}}<br>{{j.busType}}</td>
  </table>

script.js:

   $scope.busDetails = {
    {
       "operatorName": "KPN",
       "busType"     : "2+1 Sleeper A/C"
    },
    {
       "operatorName": "KPN",
       "busType"     : "2+2 Pushback Non A/C"
    },
     {
       "operatorName": "KPN",
       "busType"     : "2+2 MultiAxle Volvo Semi Sleeper A/C"
    },
     {
       "operatorName": "KPN",
       "busType"     : "2+1 Sleeper Non A/C"
    }
    }

来自这个JSON,如果我尝试过滤A / C总线,我也会得到非A / C总线。提前谢谢。

1 个答案:

答案 0 :(得分:0)

当您修复代码中的小错误时,它确实有效。 Fiddle

您的JSON无效,它应如下所示:

$scope.busDetails = [{
    "operatorName": "KPN",
    "busType": "2+1 Sleeper A/C"
  }, {
    "operatorName": "KPN",
    "busType": "2+2 Pushback Non A/C"
  }, {
    "operatorName": "KPN",
    "busType": "2+2 MultiAxle Volvo Semi Sleeper A/C"
  }, {
    "operatorName": "KPN",
    "busType": "2+1 Sleeper Non A/C"
  }];

此外,ng-repeat不应该放在桌面上,而应放在上:

<div class="col-md-3">
    <label for="type">Bus Type</label>
    <select name="busType" id="busType" ng-model="type">
      <option>A/C</option>
      <option>Non A/C</option>
      <option>Sleeper</option>
      <option>Semi Sleeper</option>
      <option>pushback</option>
      <option>MultiAxle</option>
    </select>
  </div>

  <table>
    <tr ng-repeat="j in busDetails | filter: type:j.busType">
      <td>{{j.operatorName}}
        <br>{{j.busType}}</td>
    </tr>
  </table>