2015-10-19 69 views
1

我想通過使用AngularJS同時使用過濾器功能和輸入搜索。我可以使用多種功能。但是我在添加文本框進行搜索時遇到了一些錯誤。有沒有辦法做到這一點?我嘗試了一些方法,但沒有人沒有工作。AngularJS過濾器(功能和輸入搜索)

在此先感謝。

實施例的代碼如下

var app = angular.module("app", []), 
 
    url = "http://www.filltext.com/?rows=50&pretty=true&fName={firstName}&age=[18,19,20,21]"; 
 

 
app.controller("controller", function($scope, $http) { 
 

 
    $http.get(url) 
 
    .success(function(resp) { 
 
     $scope.list = resp; 
 
    }); 
 

 
    $scope.filterAge = function(item) { 
 
    return item.age > 19; 
 
    }; 
 

 
});
<!DOCTYPE html> 
 
<html ng-app="app"> 
 

 
<head> 
 
    <script src="https://code.jquery.com/jquery.min.js"></script> 
 
    <link href="https://netdna.bootstrapcdn.com/twitter-bootstrap/2.3.2/css/bootstrap-combined.min.css" rel="stylesheet" type="text/css" /> 
 

 
    <script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.26/angular.min.js"></script> 
 
    <meta charset="utf-8"> 
 
    <title>AngularJS Filter</title> 
 
</head> 
 

 
<body ng-controller="controller"> 
 
    <div class="container"> 
 
    <br> 
 
    <input type="text" ng-model="search" placeholder="Search..." /> 
 
    <table class="table table-striped"> 
 
     <thead> 
 
     <th>Name</th> 
 
     <th>Age</th> 
 
     </thead> 
 
     <tbody> 
 
     <tr ng-repeat="item in list | filter: filterAge"> 
 
      <td>{{ item.fName }}</td> 
 
      <td>{{ item.age }}</td> 
 
     </tr> 
 
     </tbody> 
 
    </table> 
 
    </div> 
 
</body> 
 

 
</html>

回答

1

您應該將自定義過濾器添加到角度模塊,而不是將過濾器功能添加到您的控制器。這是例子:

CustomFilter:

.filter('filterByAge', function filterByAge() { 
    return function(array, age) { 
    var filteredArray = []; 

    angular.forEach(array, function(item) { 
     if (item.age > age) { 
     filteredArray.push(item); 
     } 
    }); 

    return filteredArray; 
    } 
}); 

HTML

<input type="text" ng-model="search" placeholder="Search..." /> 
<table class="table table-striped"> 
    <thead> 
    <th>Name</th> 
    <th>Age</th> 
    </thead> 
    <tbody> 
    <tr ng-repeat="item in list | filter: search | filterByAge:19"> 
     <td>{{ item.fName }}</td> 
     <td>{{ item.age }}</td> 
    </tr> 
    </tbody> 
</table> 
0
$scope.$watch('search', function (data) { 
    //sorting logic 
}) 

觀察者正在等待關於搜索日提交的,則執行該函數採取的任何行動。