0

我需要一个过滤器,使用 ngRepeat 过滤表中显示的结果。我想根据用户输入过滤这些结果。

在这一点上,我正在做这样的事情:

//HTML
<input type="search" ng-model="search">

<table>
  <tr ng-repeat="person in clients | filter: searchFilter">
    <td><input type="text" ng-model="person.Vorname"></td>            
  </tr>
</table>

控制器/过滤器功能:

app.controller('MyCtrl',function($scope){
  $scope.searchFilter = function (obj) {
    var re = new RegExp($scope.search, 'i');
    return !$scope.search || re.test(obj.Vorname) || re.test(obj.Firma);
  };
});

一切都很好。但是,我不确定我这样做是否正确。

为了符合标准,我应该将过滤器功能移动到实际的 angular.filter 吗?

如果是这样,我应该如何将输入元素中的值传递给过滤器?我知道我可以通过范围本身,但这似乎有点错误/太依赖于范围。

去这里的路是什么?

4

1 回答 1

1

为了符合标准,我应该将过滤器功能移动到实际的 angular.filter 吗?

是的,将过滤器用作实用程序的更好方法(例如作为服务、提供者、工厂的单例)。

过滤器不使用$scope它根据输入创建输出,因此您可以编写过滤器,如下所示:

app.filter('myfilter', function() {
   return function( items, types) {
    var filtered = [];

    angular.forEach(items, function(item) {
       // <some conditions>
          filtered.push(item);  // dummy usage, returns the same object         
        }
    });

    return filtered;
  };
});

取自Fiddle演示

作为参考

如果您将 codeigniter 框架与angular seed一起使用,您可以看到它们使用名为:

filters.js      --> custom angular filters 

项目结构如下:

app/                --> all of the files to be used in production
  css/              --> css files
    app.css         --> default stylesheet
  img/              --> image files
  index.html        --> app layout file (the main html template file of the app)
  index-async.html  --> just like index.html, but loads js files asynchronously
  js/               --> javascript files
    app.js          --> application
    controllers.js  --> application controllers
    directives.js   --> application directives
    filters.js      --> custom angular filters
    services.js     --> custom angular services
  lib/              --> angular and 3rd party javascript libraries
    angular/
      angular.js        --> the latest angular js
      angular.min.js    --> the latest minified angular js
      angular-*.js      --> angular add-on modules
      version.txt       --> version number
  partials/             --> angular view partials (partial html templates)
    partial1.html
    partial2.html
于 2013-11-14T07:42:16.693 回答