ng-repeat 指令會重復一個 HTML 元素
有時接收到的數據不需要全部顯示到頁面上,這時就可以使用過濾器。過濾器可以使用一個管道字符(|)添加到表達式和指令中。 可參考AngularJS 過濾器
本示例通過自定義過濾器,過濾出指定對象數組中指定key為指定value的對象。
頁面代碼
<!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代碼
<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()函數