为什么针对搜索词的AngularJS ng-repeat过滤器不起作用?

时间:2017-05-11 00:45:03

标签: html angularjs angularjs-directive angular-filters

我正在尝试创建一个过滤表,只显示包含搜索框中任何字符串的行。我有一个简单的例子,我只是想基于w3schools tutorial开始工作: https://www.w3schools.com/angular/tryit.asp?filename=try_ng_tables_css

这是我的过滤器 Rails.application.eager_load! ActiveRecord::Base.subclasses

它看起来与API参考中给出的示例非常相似:<tr ng-repeat="x in names | filter:searchKeyword"> https://docs.angularjs.org/api/ng/filter/filter

问题是当我在搜索框中输入内容时没有任何反应。我希望表随着搜索词的变化而动态变化。我错过了什么?

这是我的代码:

<tr ng-repeat="friend in friends | filter:searchText">

1 个答案:

答案 0 :(得分:4)

你只需要将输入框放在你的应用程序中:)此外,DOM过滤器很糟糕(将$filter注入你的控制器)。了解原因:https://toddmotto.com/use-controller-filters-to-prevent-digest-performance-issues/

(只需按要求将我的评论放在答案表格中。)

&#13;
&#13;
    var app = angular.module('myApp', []);
    app.controller('customersCtrl', function($scope) {
        $scope.names = [
        {"Name":"Alfreds Futterkiste","City":"Berlin","Country":"Germany"}, 
        {"Name":"Ana Trujillo Emparedados y helados","City":"México D.F.","Country":"Mexico"}, 
        {"Name":"Antonio Moreno Taquería","City":"México D.F.","Country":"Mexico"}, 
        {"Name":"Around the Horn","City":"London","Country":"UK"}, 
        {"Name":"B's Beverages","City":"London","Country":"UK"}, 
        {"Name":"Berglunds snabbköp","City":"Luleå","Country":"Sweden"}, 
        {"Name":"Blauer See Delikatessen","City":"Mannheim","Country":"Germany"}, 
        {"Name":"Blondel père et fils","City":"Strasbourg","Country":"France"}, 
        {"Name":"Bólido Comidas preparadas","City":"Madrid","Country":"Spain"}, 
        {"Name":"Bon app'","City":"Marseille","Country":"France"}, 
        {"Name":"Bottom-Dollar Marketse","City":"Tsawassen","Country":"Canada"}, 
        {"Name":"Cactus Comidas para llevar","City":"Buenos Aires","Country":"Argentina"}, 
        {"Name":"Centro comercial Moctezuma","City":"México D.F.","Country":"Mexico"}, 
        {"Name":"Chop-suey Chinese","City":"Bern","Country":"Switzerland"}, 
        {"Name":"Comércio Mineiro","City":"São Paulo","Country":"Brazil"}
        ];
    });
&#13;
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>
<div ng-app="myApp" ng-controller="customersCtrl"> 
    <label>Search: <input type="text" ng-model="searchKeyword"></label>
    <table>
      <tr ng-repeat="x in names | filter:searchKeyword">
        <td>{{ x.Name }}</td>
        <td>{{ x.Country }}</td>
        <td>{{ x.City }} </td>
      </tr>
    </table>
</div>
&#13;
&#13;
&#13;