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

來源:互聯網
上載者:User

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

  這篇文章主要簡單介紹了AngularJS中使用factory和service的方法,主要針對自訂工廠和服務的建立來講,需要的朋友可以參考下

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

  AngularJS提供例如許多內在的服務,如:$http, $route, $window, $location等。每個服務負責例如一個特定的任務,$http是用來建立AJAX調用,以獲得伺服器的資料。 $route用來定義路由資訊等。內建的服務總是首碼$符號。

  有兩種方法來建立服務。

  工廠

  服務

  使用Factory 方法

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

  ?

1

2

3

4

5

6

7

8

var mainApp = angular.module("mainApp", []);

mainApp.factory('MathService', function() {

var factory = {};

factory.multiply = function(a, b) {

return a * b

}

return factory;

});

  使用服務方法

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

  ?

1

2

3

4

5

mainApp.service('CalcService', function(MathService){

this.square = function(a) {

return MathService.multiply(a,a);

}

});

  例子

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

  testAngularJS.html

  ?

 

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

17

18

19

20

21

22

23

24

25

26

27

28

29

30

31

32

33

34

35

36

<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>

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.