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()函数