寻找更优雅的方式来解决这个任务

时间:2015-10-23 16:21:06

标签: javascript angularjs

我是Angular的新手,我正在寻找一种更优雅的方式来解决这个问题。

Code bellow工作得很好,但我不确定这是否是完成它的正确方法。

HTML

<div ng-app="ngFilterApp" ng-controller="namesCtrl">
    <p>Filtering input:</p>

    <p><input type="text" ng-model="search" /></p>
    <ul>
        <li ng-repeat="x in names | myFilter">
            {{ x.name + ', ' + x.country }}
        </li>
    </ul>
</div>

JS

var searchVal;
angular.module('CustomFilterModule', [])
  .filter('myFilter', function() {
  return function( input ) {
    searchVal = searchVal || '';
    var s = searchVal.toLowerCase();
    var arr = [];
    for (var i = 0; i < input.length; i++) {
      if(input[i].name.toLowerCase().indexOf(s) === 0 || input[i].country.toLowerCase().indexOf(s) === 0) arr.push(input[i]);
    }

    return arr;
  };
});

angular.module('ngFilterApp', ['CustomFilterModule'])
  .controller('namesCtrl', function($scope) {
  $scope.names = [
    {name:'Moscow',country:'Russia'},
    {name:'Kiev',country:'Ukraine'},
    {name:'Yerevan',country:'Armenia'},
    {name:'Washington',country:'USA'},
    {name:'Madrid',country:'Spain'},
    {name:'Tbilisi',country:'Georgia'}
  ];

  $scope.$watch('search', function() { searchVal = $scope.search; }, true);
});

JSBIN http://jsbin.com/bomotocota/edit?html,js,output

1 个答案:

答案 0 :(得分:0)

您可以将查询字符串作为参数传递给过滤器,请参阅修改后的JSBIN:

http://jsbin.com/yivomusoso/edit?html,js,output