簡體   English   中英

過濾結果以顯示與ng-show angular js匹配的結果

[英]filter results to show matching results with ng-show angular 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-show做到這一點,到目前為止我只能這樣做

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完成嗎? 有沒有更好的辦法?

您想要創建自定義過濾器。 它可以很容易地完成。 此過濾器將根據搜索測試您朋友的姓名。 如果

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

我認為這樣做會更容易:

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

此外,過濾器將應用於所有屬性,而不僅僅是名稱。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM