有時接收到的數據不須要所有顯示到頁面上,這時就能夠使用過濾器。過濾器能夠使用一個管道字符(|)添加到表達式和指令中。 可參考AngularJS 過濾器
本示例經過自定義過濾器,過濾出指定對象數組中指定key爲指定value的對象。javascript
頁面代碼html
<!DOCTYPE html> <html> <head> <meta charset="utf-8" /> <script src="https://cdn.staticfile.org/angular.js/1.4.6/angular.min.js"></script> <style> ul > li { list-style: none } .active { background-color: red!important; border: 1px solid #000000; } </style> </head> <body> <div ng-app="myApp" ng-controller="myCtrl"> <ul> <!-- 動態設置寬高 ,顯示知足指定屬性值的數據--> <li ng-repeat="(i,item) in names | filterRow :'width':300" ng-class="{'active': item.width === 100}" style="background-color: skyblue;width:{{ item.width }}px; height: {{ (i+1) * 100 }}px;"> {{ item.name + ", " + item.country }} --> {{(i*i+10)*20}} </li> </ul> </div> </body> </html>
JS代碼java
<script> var app = angular.module("myApp", []) app.controller("myCtrl", function($scope) { $scope.names = [ {width:100, name: "Jani", country: "Norway" }, {width:200, name: "Hege", country: "Sweden" }, {width:300, name: "Kai", country: "Denmark" } ]; }); // 設置過濾器,過濾指collection中keyName值爲value的數據 app.filter('filterRow',function(){ return function(collection,keyName,value){ var output = [] angular.forEach(collection, function (item) { console.log("item[keyName]->"+item[keyName]) if(item[keyName] === value){ output.push(item) } }) console.log(output.length) return output }; }) </script>
能夠根據實際狀況自定義filter中function()函數angularjs