2014-11-04 93 views
1

我可以在下面所有条目出现在页面上的搜索结果进行过滤筛选结果显示与NG-显示角度JS匹配结果

<body ng-app=""> 
     <div ng-init="friends = [{name:'John', phone:'555-1276'}, 
           {name:'Mary', phone:'800-BIG-MARY'}, 
           {name:'Mike', phone:'555-4321'}, 
           {name:'Adam', phone:'555-5678'}, 
           {name:'Julie', phone:'555-8765'}, 
           {name:'Juliette', phone:'555-5678'}]"></div> 

     Search: <input ng-model="searchText"> 
     <table id="searchTextResults"> 
     <tr><th>Name</th><th>Phone</th></tr> 
     <tr ng-repeat="friend in friends | filter:searchText"> 
      <td>{{friend.name}}</td> 
      <td>{{friend.phone}}</td> 
     </tr> 
     </table> 
    </body> 

我想实现是一个jQuery UI自动完成型解决方案,最初页面上没有任何内容,但在输入匹配的条目时出现。

我想我也许能NG-节目要做到这一点,到目前为止,我只能例如

ng-show="searchText == 'John'" 

这意味着它将永远是空白的,除非你在约翰键入做。 有没有一种方法与ng-show或ng-if筛选(显示匹配的条目),就像过滤器一样输入? 我有下面展示我的约翰例如

<body ng-app=""> 
     <div ng-init="friends = [{name:'John', phone:'555-1276'}, 
           {name:'Mary', phone:'800-BIG-MARY'}, 
           {name:'Mike', phone:'555-4321'}, 
           {name:'Adam', phone:'555-5678'}, 
           {name:'Julie', phone:'555-8765'}, 
           {name:'Juliette', phone:'555-5678'}]"></div> 

     Search: <input ng-model="searchText"> 
     <table id="searchTextResults"> 
     <tr><th>Name</th><th>Phone</th></tr> 
     <tr ng-repeat="friend in friends | filter:searchText" ng-show="searchText == 'John'"> 
      <td>{{friend.name}}</td> 
      <td>{{friend.phone}}</td> 
     </tr> 
     </table> 
    </body> 

我也试过

 ng-show="searchText == searchText" 

但这恰恰显示了所有项目? 这可以用ng-show来完成吗? 有没有更好的方法?

回答

3

您想要创建自定义过滤器。它可以很容易地完成。此筛选器将根据搜索测试朋友的姓名。如果

app.filter('filterFriends', function() { 
    return function(friends, search) { 
     if (search === "") return friends; 
     return friends.filter(function(friend) { 
      return friend.name.match(search); 
     }); 
    } 
}); 

这应该给你如何创建过滤器是个好主意,并且只要你喜欢,你可以自定义它。在你的HTML中,你会像这样使用它。

<input ng-model="search"> 
<tr ng-repeat="friend in friends | filterFriends:search"> 
    <td>{{friend.name}}</td> 
    <td>{{friend.phone}}</td> 
</tr> 

这是JSFiddle

+0

你还没有在任何地方定义'list'变量。可以用'[]'替换它。 – miqid 2014-11-05 00:18:05

+0

它应该说'朋友'。我重命名了变量并错过了那个变量。我的错。 – 2014-11-05 00:30:50

0

我认为这将是更容易只是做:

<tr ng-repeat="friend in friends" ng-show="([friend] | filter:search).length > 0"> 
    <td>{{friend.name}}</td> 
    <td>{{friend.phone}}</td> 
</tr> 

而且这样的过滤器将应用到所有属性,而不仅仅是名字。