zoukankan      html  css  js  c++  java
  • angular学习笔记(十五)-module里的'服务'

    什么是 '服务' 呢? 看一下下面这个例子:

    比如一个购物车的应用:

    复制代码
    function ItemsViewController($scope){
    
       //向服务器发起请求
    
       //解析响应,获得数据
    
       $scope.items = 获得的数据;
    
    }
    复制代码

    那么,如果我在其它的控制器里也需要同样的一组数据,那么,我还得在另外的控制器里写一遍一样的代码,用于获取这组数据,

    这样不利于维护修改,因此,我们就可以把 '获取这一段数据' 这个功能给封装成一个 '服务' , 这样就可以在多个不同的控制器中使用它.

    function ItemsViewController($scope,Items){
    
       $scope.items = Items.query();
    
    }

    比如这里的Items就是一个被封装好的 '服务' .

    下面来看看如果创建服务:

    1. 首先要创建一个模块:

    var SomeModule = angular.module('ModuleName',[]) 

    2. 然后通过以下三种api来创建服务:

      ①SomeModule.provider(name,Object || constructor())

      ②SomeModule.factory(name,$get Function())

      ③SomeModule.service(name,constructor())

    其中第一个参数应该是字符串形式,定义的是服务的名字

    第二个参数需要通过例子来理解... 而且后面还会有详解.在这里先不介绍

     

    最后使用'服务'来完成购物车的例子:

    复制代码
    <!DOCTYPE html>
    <html ng-app="shoppingCart">
    <head>
      <title>12.1module模块组织依赖关系</title>
      <meta charset="utf-8">
      <script src="../angular.js"></script>
      <script src="script.js"></script>
    </head>
    <body>
    <div ng-controller="CartController">
      <h1>your shopping cart</h1>
      <table>
        <tr ng-repeat="item in items">
          <td>{{item.title}}</td>
          <td><input ng-model="item.quantity"/></td>
          <td>{{item.price|currency}}</td>
          <td class="red">{{item.price*item.quantity|currency}}</td>
          <td><button ng-click="remove($index)">remove</button></td>
        </tr>
      </table>
      <hr>
      <table>
        <tr>
          <td>总价: <span class="del">{{bill.all|currency}}</span></td>
        </tr>
        <tr>
          <td>折扣: <span class="red">{{bill.discount|currency}}</span></td>
        </tr>
        <tr>
          <td>现价: <span class="green">{{bill.now|currency}}</span></td>
        </tr>
      </table>
    </div>
    </body>
    </html>
    复制代码
    复制代码
    var shoppingCart = angular.module('shoppingCart',[]);
    shoppingCart.factory('Items',function(){
        var items = {};
        //这段数据实际应该是从数据库拉取的
        items.query = function(){
            return [
                {"title":"兔子","quantity":1,"price":"100"},
                {"title":"喵","quantity":2,"price":"200"},
                {"title":"狗只","quantity":1,"price":"400"},
                {"title":"仓鼠","quantity":1,"price":"300"}
            ]
        };
        return items;
    });
    shoppingCart.controller('CartController',function($scope,Items){
        $scope.items = Items.query();
        $scope.remove = function(index){
            $scope.items.splice(index,1)
        };
        $scope.bill = {
            "all":0,
            "discount":0,
            "now":0
        };
        $scope.compute = function(){
            var total = 0;
            for(var i=0; i<$scope.items.length; i++){
                total += $scope.items[i].quantity*$scope.items[i].price;
            }
            $scope.bill.all = total;
            $scope.bill.discount = total >= 500 ? total*0.1 : 0 ;
            $scope.bill.now = $scope.bill.all - $scope.bill.discount
        };
        $scope.$watch('items',$scope.compute,true);
    });
    复制代码

     

      1. var shoppingCart = angular.module('shoppingCart',[]);

    注意, 第一个shoppingCart 是模型变量名,下面的factory和controller,都是该模型下的方法.第二个shoppingCart是模型的名字,在ng-app后面使用 


    2.shoppingCart.factory('Items',function(){ ... return items; });

    Items就是服务的名字

    第二个参数是一个函数,在调用这个服务的时候,就会执行该函数,然后把函数的返回值传到控制器中
    shoppingCart.controller('CartController',function($scope,Items){
        $scope.items = Items.query();    
    });
    这里在控制器中传入的Items就是factory中第二个参数的函数的返回值
    注意,当Items被注入到其它地方的时候,注入的结果是items,而不是定义Items的时候的那个function

    3. shoppingCart.controller('CartController',function($scope,Items){
    $scope.items = Items.query();
        ...
    });

    通过controller方法,在shoppingCart模型下创建一个名为CartController的控制器,传入Items服务
    其余的控制器写法都和原来一样,只是原来的items改为通过Items服务来获取数据

    4. 其实$scope也是服务,是angular内置的服务,还有$location,$route,$http等... angular内置的服务,都是用$开头,因此,自定义的服务,最好不要使用$开头.
    5. 控制器中传入服务作为参数,是没有顺序的,是根据名字来的.以下两种写法运行结果是一致的:
    shoppingCart.controller('CartController',function($scope,Items){...});
    shoppingCart.controller('CartController',function(Items,$scope){...});
  • 相关阅读:
    Appium安装说明
    解决上传到github报错Successfully created project 'autotest' on GitHub, but initial commit failed:
    解决Robot Framework运行时没有Log的方案
    Robot Framework问题汇总...不断更新中
    Jmeter常见问题汇总(不断更新ing)
    自动化测试基础篇--小结
    自动化测试基础篇--Selenium发送测试报告邮件
    自动化测试基础篇--Selenium unittest生成测试报告(HTMLTestRunner)
    自动化测试基础篇--Selenium unittest简介
    自动化测试基础篇--Selenium框架设计(POM)
  • 原文地址:https://www.cnblogs.com/minghui007/p/7205700.html
Copyright © 2011-2022 走看看