angular實現商品篩選功能(過濾器)
阿新 • • 發佈:2019-01-09
一、demo功能分析
1、通過service()建立資料並遍歷渲染到頁面
2、根據輸入框的輸入值進行欄位查詢
3、點選各列實現排序功能。
二、實現
1.1 資料定義與渲染
angular更偏向於是一個MVVM模式的框架,所以它的controller很薄,裡面的業務邏輯也是少的,因此應該養成把邏輯寫在service或者Factory等angular提供的可以自定義服務的方法中。此次demo通過angular的service方法來註冊並定義商品資料。
angular.module("app",[])
.service("productData",function(){
//通過service方法來定義資料,也可以通過factory方法來定義
return [
{
id:1002,
name:'HuaWei',
quantity:200,
price:4300
},
{
id:2123,
name:'iphone7',
quantity:38,
price:6300
},
{
id:3001,
name:'XiaoMi',
quantity:3 ,
price:2800
},
{
id:4145,
name:'Oppo',
quantity:37,
price:2100
},
{
id:5563,
name:'Vivo',
quantity:23,
price:2100
}
]
})
//傳入用service定義的productData資料依賴
.controller("myCtrl" ,function($scope,productData){
$scope.data=productData; //進行相應賦值
$scope.order=''; //單列排序用,後面詳解
$scope.changeOrder=function(type){
$scope.orderType=type;
if($scope.order===''){
$scope.order='-';
}else{
$scope.order='';
}
}
})
資料渲染部分:
<table class="table">
<thead>
<tr>
<th ng-class="{dropup:order===''}" ng-click="changeOrder('id')">產品編號<span class="caret"></span></th>
<th ng-class="{dropup:order===''}" ng-click="changeOrder('name')">產品各稱<span class="caret"></span></th>
<th ng-class="{dropup:order===''}" ng-click="changeOrder('price')">產品價錢<span class="caret"></span></th>
</tr>
</thead>
<tbody>
<tr ng-repeat="value in data|filter:{id:search}|orderBy:order+orderType">
<td>{{value.id}}</td>
<td>{{value.name}}</td>
<td>{{value.price}}</td>
</tr>
</tbody>
</table>
說明:上面利用了bootstrap的caret類名來顯示出三角符號,並通過給父元素加dropup使三角符號轉向。
1、三角符號的轉向與否由ng-class指令確定,傳入表示式,當order===‘ ’時,為true,則給th加上dropup類名
2、用ng-click指令繫結點選事件,實現點選就切換排序方式
2.2 搜尋功能
採用angular的filter過濾器,搜尋輸入欄位
<!--輸入框採用ng-model繫結一個值-->
搜尋:<input type="text" ng-model="search">
<!--通過filter:{id:search}實現以id為搜尋內容,以search的值為搜尋基準-->
<tr ng-repeat="value in data|filter:{id:search}|orderBy:order+orderType">
<td>{{value.id}}</td>
<td>{{value.name}}</td>
<td>{{value.price}}</td>
</tr>
2.3 排序功能
1、定義order屬性用於設定正序還是反序
2、定義orderType屬性用於設定參考排序的值
3、定義changeOrder()方法用於實現點選就切換排序的功能
$scope.order=''; //當order為‘’時正序
$scope.changeOrder=function(type){ //傳入屬性名,以此為基準排序
$scope.orderType=type;
if($scope.order===''){
$scope.order='-'; //order為'-'時,反序
}else{
$scope.order='';
}
}
頁面中:changeOrder()函式傳入“型別”作為引數,並在函式內部通過\ $scope.orderType=type;設定排序的參考型別
<table class="table">
<thead>
<tr>
<th ng-class="{dropup:order===''}" ng-click="changeOrder('id')">產品編號<span class="caret"></span></th>
<th ng-class="{dropup:order===''}" ng-click="changeOrder('name')">產品各稱<span class="caret"></span></th>
<th ng-class="{dropup:order===''}" ng-click="changeOrder('price')">產品價錢<span class="caret"></span></th>
</tr>
</thead>
<tbody>
<tr ng-repeat="value in data|filter:{id:search}|orderBy:order+orderType">
<td>{{value.id}}</td>
<td>{{value.name}}</td>
<td>{{value.price}}</td>
</tr>
</tbody>
</table>