一、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>以上就是本文的全部內容,希望對大家的學習有所幫助,也希望大家多多支持武林網。
新聞熱點
疑難解答