简介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。看到结果如下。


« 
» 
快速导航

Copyright © 2016 phpStudy | 豫ICP备2021030365号-3