我生待明日,万事成蹉跎

AngularJS简单入门(5)

1、$provider 自定义服务,provider的$get()中得到的对象就可依赖注入到服务中,此服务就可放入controller中使用(通常不自定义,因为有很多简便的方法)

<body style="padding:40px" ng-app="MyApp">
      <div ng-controller="myController">
          通常不自定义服务,因为有很多简便的方法
      </div>

      <div ng-controller="filterController">
          filter过滤示例:<br>
          {{city}}
           {{city | filter:'成都'}}
      </div>
</body>

<script>
var app=angular.module('MyApp',[],function($provide){
    //自定义服务
    $provide.provider('myPro',function(){
       this.$get=function(){
           return{
               msg:"hehehehehehehehehehehehehe"
           }
       }
    });
    //自定义工厂
    $provide.factory('myFac',function(){
        return ['dd','fg','sdfsd']//可返回对象、字符串、数字
    });
    //自定义服务
    $provide.service('myService',function(){
        return [1,2,4,5,6,7];//只可返回对象(数组也是对象)
    })
});
app.controller('myController',function($scope,myPro,myFac,myService){
    console.log(myPro);
    console.log(myFac);
    console.log(myService);
});
app.controller('filterController',function($scope){
   $scope.city=[
       {name:"成都",py:"cd"},
       {name:"上海",py:"sh"},
       {name:"成都周边",py:"cd"}
   ]
});
</script>

2、$filter过滤器的其它使用(完善上篇文章的购物车:排序、格式、搜索)

<body style="padding:40px" ng-app="MyApp">
      <div class="container" ng-controller="carController">
          <nav class="navbar navbar-default">
              <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" class="form-control" placeholder="Search" ng-model="search">
                          </div>
                      </form>
                  </div><!-- /.navbar-collapse -->
              </div><!-- /.container-fluid -->
          </nav>
          <table class="table table-striped" ng-show="cart.length">
              <thead>
              <tr>
                  <th ng-class="{dropup:order===''}" ng-click="changeOrder('id')">
                      产品编号
                  <span class="caret" ng-class="{orderColor:ordertype==='id'}"></span>
                  </th>
                  <th>产品名字</th>
                  <th ng-class="{dropup:order==='-'}" ng-click="changeOrder('quantity')">
                      购买数量
                      <span class="caret" ng-class="{orderColor:ordertype==='quantity'}"></span>
                  </th>
                  <th ng-class="{dropup:order===''}"  ng-click="changeOrder('price')">
                      产品单价
                      <span class="caret" ng-class="{orderColor:ordertype==='price'}"></span>
                  </th>
                  <th>
                      产品总价
                  </th>
                  <th>操作</th>
              </tr>
              </thead>
              <tbody>
              <tr ng-repeat="m in cart | filter:{name:search} | orderBy : order+ordertype">
                            <!--<tr ng-repeat="m in cart | filter:name">-->
                  <td>{{m.id}}</td>
                  <td>{{m.name}}</td>
                  <td>
                      <button type="button" ng-click="del(m.id)" class="btn btn-primary">-</button>
                      <input type="text" value="{{m.quantity}}" ng-model="m.quantity">
                      <button type="button" ng-click="add(m.id)" class="btn btn-primary">+</button>

                  </td>
                  <td>{{m.price | currency}}</td>
                  <td>{{m.price * m.quantity |currency:'(¥)'}}</td>
                  <td>
                      <button type="button" class="btn btn-danger"
                              ng-click="removeFunc(m.id)">移除</button>
                  </td>
              </tr>
              <tr>
                  <td>总购买价</td>
                  <td>{{totalPriceFunc()}}</td>
                  <td>总购买数量</td>
                  <td>{{totalnumFunc()}}</td>
                  <td colspan="2">
                      <button type="button" class="btn btn-danger"
                              ng-click="cart={}">清空购物车</button>
                  </td>
              </tr>
              </tbody>
          </table>
          <p ng-show="!cart.length">购物车为空</p>
      </div>
</body>
<script type="text/javascript">
    angular.module("MyApp", [])
        .controller("carController", function ($scope,$filter) {
             $scope.cart=[
                 {
                     id:10,
                     name:"Tshirt",
                     quantity:3,
                     price:2300
                 },
                 {
                     id:20,
                     name:"iphone6s",
                     quantity:2,
                     price:5300
                 },
                 {
                     id:30,
                     name:"pingpong",
                     quantity:10,
                     price:30
                 },
                 {
                     id:40,
                     name:"football",
                     quantity:29,
                     price:460
                 }
             ];
            //总价:
            $scope.totalPriceFunc=function(){
                var totalprice=0;
                angular.forEach($scope.cart,function(im){
                    totalprice+=im.quantity*im.price;
                })
                return $filter('currency')(totalprice);
            };
            //总数量:
            $scope.totalnumFunc=function(){
                var totalnum=0;
                angular.forEach($scope.cart,function(im){
                    totalnum+=parseInt(im.quantity);
                })
                return totalnum;
            };
            //移除
            $scope.removeFunc=function(id){
                var index=-1;
                angular.forEach($scope.cart,function(m,thekey){
                    if(m.id===id){
                        index=thekey;
                        return;
                    }
                });
                if(index!==-1){//理论上讲 thekey的值一定能取到
                    $scope.cart.splice(index,1);//第一个参数:删除的起始下标  第二个参数:删除个数
                }
            }

            //数量的增减

                      //找到当前索引
                      var findIndex=function(id){
                          var index=-1;
                         angular.forEach($scope.cart,function(m,key){
                            if(m.id===id){
                                 index=key;
                                return;
                            }
                         });
                          return index;
                      }
                     //增加数量
                     $scope.add=function(id){
                         var theindex=findIndex(id);
                         if(theindex!==-1){
                             ++$scope.cart[theindex].quantity;
                         }
                     }
                     //减去数量
                      $scope.del=function(id){
                          var theindex=findIndex(id);
                          if(theindex!==-1){
                              var theshopNum=$scope.cart[theindex].quantity;//当前商品数量
                              if(theshopNum>1){
                                  --$scope.cart[theindex].quantity;
                              }else{
                                  var msg=confirm('是否从购物车删除该商品?');
                                  if(msg){
                                      $scope.removeFunc(id);
                                  }
                              }
                          }
                      }
            //自动脏检查(看输入框输入的数量是否符合要求)
            $scope.$watch('cart',function(newValue,oldValue){
                angular.forEach(newValue,function(m,index){
                    if(m.quantity<1){
                        var msg=confirm('是否从购物车删除该商品?');
                        if(msg){
                            $scope.removeFunc(m.id);
                        }else{
                            m.quantity=newValue[index].quantity;
                        }
                    }
                });
            },true);
            //过滤器
            $scope.ordertype="id";
            $scope.order="-";//代表降序

            $scope.changeOrder=function(type){
                $scope.ordertype=type;
                if($scope.order===''){
                    $scope.order='-';
                }else{
                    $scope.order='';
                }
            }
        })
</script>

3、ng-class 当表达式发生变化,先前添加的类会被移除,新类会被添加

未经允许不得转载:徐宏涛博客 » AngularJS简单入门(5)

分享到:更多 ()

评论 抢沙发

评论前必须登录!