angular學習筆記(十五)-module裡的'服務'

詩&遠方發表於2014-05-14

本篇介紹angular中的模組:module

在筆記(二)http://www.cnblogs.com/liulangmao/p/3711047.html裡已經講到過模組,這篇主要講模組的 '服務' 功能:

什麼是 '服務' 呢? 看一下下面這個例子:

比如一個購物車的應用:

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){...});


 

相關文章