本例展示产品列表,使用angular过滤器 orderBy对产品进行排序,具体是点击列标题时交替进行正序倒序排列;同时使用angular过滤器 filter 可根据输入的产品名称搜索出对应产品,实现模糊查询。
页面运行如下:
输入"pad" 则自动显示相关产品,点击“产品价格”按价格低到高排序:
html:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Title</title>
<link rel="stylesheet" href="../../vendor/bootstrap3/css/bootstrap.css">
<script src="http://cdn.static.runoob.com/libs/angular.js/1.4.6/angular.min.js"></script>
<script src="app/index2.js"></script>
<style>
.redColor{ color:red; }
</style>
</head>
<body>
<div class="container" ng-app="product" ng-controller="productController">
<nav class="navbar navbar-default" role="navigation">
<div class="container-fluid">
<div class="collapse navbar-collapse" id="bs-example-navbar-collapse-1">
<form class="navbar-form navbar-left" role="search">
<div class="form-group">
<input type="text" ng-model="search" class="form-control" placeholder="产品名称">
</div>
</form>
</div><!-- /.navbar-collapse -->
</div><!-- /.container-fluid -->
</nav>
<table class="table">
<thead>
<tr>
<th ng-click="sortProduct('id')" ng-class="{ dropup : orderSign=='' }">
产品编号
<span ng-class="{ redColor : orderColumn=='id' }" class="caret"></span>
</th>
<th ng-click="sortProduct('name')" ng-class="{ dropup : orderSign=='' }">
产品名称
<span ng-class="{ redColor : orderColumn=='name' }" class="caret"></span>
</th>
<th ng-click="sortProduct('price')" ng-class="{ dropup : orderSign=='' }">
产品价格
<span ng-class="{ redColor : orderColumn=='price' }" class="caret"></span>
</th>
</tr>
</thead>
<tbody>
<tr ng-repeat="item in productList | filter:{'name':search} | orderBy:(orderSign + orderColumn) ">
<td>
{{item.id}}
</td>
<td>
{{item.name}}
</td>
<td>
{{item.price | currency:'(RMB)'}}
</td>
</tr>
</tbody>
</table>
</div>
</body>
</html>
index2.js
angular.module('product',[])
.factory('productList',function(){
return [
{ id:910,name:"imac",price:15400 },
{ id:80,name:"iphone",price:5400 },
{ id:29,name:"ipad",price:1420 },
{ id:500,name:"ipad air",price:2340 },
{ id:1200,name:"ipad mini",price:2200 }
]
})
.controller('productController',function($scope,productList){
$scope.productList=productList;
$scope.orderColumn='name'; //排序字段
$scope.orderSign='-'; //为空时正序 为负号时倒序
$scope.sortProduct=function(sortColumn){ //点击列标题排序事件
$scope.orderColumn=sortColumn;
if($scope.orderSign=="-"){
$scope.orderSign="";
}else{
$scope.orderSign='-';
}
};
});
相关指令:
ng-class 示例: ng-class=" { redColor : bool表达式 } " ,redColor 是一个css样式类
如果bool表达式值为真,则添加这个样式 redColor
重点:
<tr ng-repeat=" item in productList | filter : {'name':search} | orderBy : '-price' ">
search是搜索框输入数据的模型 ,
| filter : {'name':search} 指明:根据搜索框的输入数据过滤产品名称 ,
| orderBy : '-price' 指明:根据产品价格由高到低排序