一、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>以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持脚本之家。