2017-02-03 41 views
0

我有一個搜索欄,讓用戶可以使用角度基於其輸入進行過濾。現在,當用戶輸入的搜索詞與數組中的任何內容不匹配時,現在我希望能夠顯示「Nothing與您的搜索相匹配」的消息。如何知道角度的過濾陣列的長度

我試着用ng-change來監視用戶的輸入,然後循環遍歷數組搜索用戶輸入的每個參數,但是這並不奏效。這是我的代碼示例。

HTML

<input ng-model="search" ng-change="check(search)"> 
<h4 ng-if="found === 0 ">Nothing matches your search</h4> 
<div ng-controller="imCtrl" ng-repeat="imprest in imprests | filter:search"> 
    <h2>{{imprest.name}}</h2> 
</div> 

控制器

var office = angular.module('Office'); 

office.controller('imCtrl',[$scope,function('$scope'){ 
    $scope.imprests = [ 
      {name:'John'}, 
      {name:'Peter'} 
    ] 

    $scope.check = function (word) { 
     var found = 0 
     $scope.searching = true 
     for (var i = 0; i < $scope.vendorForms.length; i++) { 
      if($scope.imprests[i].name.includes(word){ 
       found++ 
      } 
     } 
     $scope.found = found 
     $scope.searching = true 
     $scope.done = true 
    } 
}) 

是否有可能知道過濾數組的長度因此可以顯示一個消息?

+0

您可以檢查這個答案 - https://stackoverflow.com/questions/15316363/how-to-display-length-of-filtered-ng-repea叔數據?RQ = 1 –

回答

1

您可以使用一個別名:

ng-repeat="imprest in imprests | filter:search as filtered" 

然後你就可以訪問:

{{filtered.length}} 
1

你可以寫一個過濾功能,並用它來過濾你的角碼的排列,然後檢查它的長度。

$scope.myFilter(){ 
    // ... here your logic 
    // you need to compare with $scope.search 
    // and then return the new array and check it's length 
} 

的標記,你可以像使用

<div ng-controller="imCtrl" ng-repeat="imprest in myFilter()"> 
    <h2>{{imprest.name}}</h2> 
</div> 
0

你應該能夠使用(imprests | filter:search).length == 0要做到這一點,然後,而不是你的ng-change功能,你可以簡單地添加一個ng-show顯示錯誤,像這樣:

<input ng-model="search"> 
<h4 ng-if="found === 0 ">Nothing matches your search</h4> 
<div ng-controller="imCtrl" ng-repeat="imprest in imprests | filter:search" ng-show="(imprests | filter:search).length !== 0"> 
    <h2>{{imprest.name}}</h2> 
</div> 
<div ng-show="(imprests | filter:search).length === 0"> 
    <h2>No results found</h2> 
</div>