2014-10-01 114 views
0

我在我的視圖中有ng-click,它應該過濾我提供的結果。在AngularJS中篩選結果

<a role="menuitem" tabindex="-1" href ng-click="itemFilter=itemABCFilter">ABC Filter</a> 

從ABC的所有項目都存儲在我的控制器,如

$scope.itemABC=["Alpha","Beta","Gamma"]; 

來自$http要求我做在我看來,所有項目的清單。不,我尋找循環遍歷所有data.item(我的數據,我從獲取請求中獲得),並找出它是否包含itemABC的任何元素,或者可以將它視爲itemABC中任何元素的子字符串。

$scope.itemABCfilter=function(data){ 
    for (var j=0; j<$scope.itemABC.length;j++){ 
     if($scope.itemABC[j].search($scope.data[i].name)>-1) return true; 
    } 

不知何故,上面的代碼不會過濾我的結果。我是否正確處理$ http請求結果,或者代碼是否錯誤?你會怎麼做?

$ http請求看起來像這樣,工作得很好。

$scope.method='GET'; 
     $scope.url='/files/itemdata.js'; 
     $scope.fetch=function(){ 
      $http({ 
       method:$scope.method, 
       headers:{'Content-Type': 'application/x-www-form-urlencoded'}, 
       cache:true 

      }) 
       .success(function(data,status){ 
        $scope.status=status; 
        $scope.data=data; 
        console.log(data); 
        console.log(status); 
        itemABCFilter(); 

       }) 
       .error(function(data,status){ 
        $scope.data=data||"Request failed"; 
        $scope.status=status; 
       }) 
     }; 

訪問HTTP請求的結果,我用數據[I]。名稱....然而,這似乎並沒有在循環工作。

+0

JavaScript'Array'沒有'search'方法。在代碼運行之前,您是否添加了一些自定義的'Array.prototype.search'實現?你有沒有調試你的代碼,控制檯中是否有錯誤? – Vadim 2014-10-01 06:45:06

+0

控制檯沒有錯誤,http請求也可以正常工作。我知道JS在數組上沒有搜索方法,但是這裏的搜索方法搜索數組的單個項目作爲子串。這不應該是個問題吧? – Dribel 2014-10-01 07:07:12

+0

如果您澄清您的問題併發布了所有相關代碼,將會對您有所幫助。你問是否正確處理$ http響應,但是你沒有顯示任何處理響應的代碼?此外,ng-click只設置「itemFilter」,但該項目篩選器不顯示在其他地方? – 2014-10-01 07:28:53

回答

1

您可以嘗試創建這種情況下,您的自定義過濾器:

HTML

<div ng-controller="ctrl"> 
    <ul> 
    <li ng-repeat="item in items | myFilter:list">{{item.name}}</li> 
    </ul> 
    <a ng-click="filterResults()">Filter results</a> 
</div> 

的JavaScript

angular.module('app', []). 
    controller('ctrl', ['$scope', '$http', function($scope, $http) { 
    $http.get('data.json').success(function(data) { 
     $scope.items = data; 
    }); 
    $scope.filterResults = function() { 
     $scope.list = ["Alpha", "Beta", "Gamma"]; 
    } 
    }]). 
    filter('myFilter', function() { 
    return function(data, list) { 
     if(data && list) { 
     return data.filter(function(item) { 
      return list.reduce(function(prev, cur) { 
      return prev || item.name.indexOf(cur) !== -1; 
      }, false); 
     }); 
     } else { 
     return data; 
     } 
    } 
    }); 

現場演示here

搜索遍及所有屬性的示例(不僅是namehere

+0

這正是我需要的!非常感謝! – Dribel 2014-10-01 08:09:20

0

如果您顯示的是一組數據結果,過濾它們的最好方法是使用過濾器,並且從我的理解中可以看出,您需要使用過濾器函數過濾多個值。

<li ng-repeat="item in items|filter:abcFilter">{{item.name}}</li> 

然後過濾功能將在範圍上提供

$scope.abcFilter = function(item){ 
    return $scope.itemABC.indexOf(item.name) > -1;  
} 

所以你可以看到,如果過濾函數返回true,則項目將被顯示。