簡介AngularJS中使用factory和service的方法


 

AngularJS支持使用服務的體系結構“關注點分離”的概念。服務是JavaScript函數,並負責只做一個特定的任務。這也使得他們即維護和測試的單獨實體。控制器,過濾器可以調用它們作為需求的基礎。服務使用AngularJS的依賴注入機制注入正常。

AngularJS提供例如許多內在的服務,如:$http, $route, $window, $location等。每個服務負責例如一個特定的任務,$http是用來創建AJAX調用,以獲得服務器的數據。 $route用來定義路由信息等。內置的服務總是前綴$符號。

有兩種方法來創建服務。

  1.     工廠
  2.     服務

使用工廠方法

使用工廠方法,我們先定義一個工廠,然后分配方法給它。

   var mainApp = angular.module("mainApp", []);
   mainApp.factory('MathService', function() {   
     var factory = {}; 
     factory.multiply = function(a, b) {
      return a * b 
     }
     return factory;
   }); 

使用服務方法

使用服務的方法,我們定義了一個服務,然后分配方法。還注入已經可用的服務。

mainApp.service('CalcService', function(MathService){
  this.square = function(a) { 
 return MathService.multiply(a,a); 
 }
});

例子

下面的例子將展示上述所有指令。
testAngularJS.html

<html>
<head>
  <title>Angular JS Forms</title>
</head>
<body>
  <h2>AngularJS Sample Application</h2>
  <div ng-app="mainApp" ng-controller="CalcController">
   <p>Enter a number: <input type="number" ng-model="number" />
   <button ng-click="square()">X<sup>2</sup></button>
   <p>Result: {{result}}</p>
  </div>
  <script src="http://ajax.googleapis.com/ajax/libs/angularjs/1.2.15/angular.min.js"></script>
  <script>
   var mainApp = angular.module("mainApp", []);
   mainApp.factory('MathService', function() {   
     var factory = {}; 
     factory.multiply = function(a, b) {
      return a * b 
     }
     return factory;
   }); 

   mainApp.service('CalcService', function(MathService){
      this.square = function(a) { 
      return MathService.multiply(a,a); 
     }
   });

   mainApp.controller('CalcController', function($scope, CalcService) {
      $scope.square = function() {
      $scope.result = CalcService.square($scope.number);
     }
   });
  </script>
</body>
</html>

結果

在Web瀏覽器打開textAngularJS.html。看到結果如下。

簡介AngularJS中使用factory和service的方法_新客網


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM