AngularJS支持使用服務(wù)的體系結(jié)構(gòu)“關(guān)注點(diǎn)分離”的概念。服務(wù)是JavaScript函數(shù),并負(fù)責(zé)只做一個(gè)特定的任務(wù)。這也使得他們即維護(hù)和測(cè)試的單獨(dú)實(shí)體??刂破鳎^(guò)濾器可以調(diào)用它們作為需求的基礎(chǔ)。服務(wù)使用AngularJS的依賴(lài)注入機(jī)制注入正常。
AngularJS提供例如許多內(nèi)在的服務(wù),如:$http, $route, $window, $location等。每個(gè)服務(wù)負(fù)責(zé)例如一個(gè)特定的任務(wù),$http是用來(lái)創(chuàng)建AJAX調(diào)用,以獲得服務(wù)器的數(shù)據(jù)。 $route用來(lái)定義路由信息等。內(nèi)置的服務(wù)總是前綴$符號(hào)。
有兩種方法來(lái)創(chuàng)建服務(wù)。
工廠(chǎng)
服務(wù)
使用工廠(chǎng)方法
使用工廠(chǎng)方法,我們先定義一個(gè)工廠(chǎng),然后分配方法給它。
var mainApp = angular.module("mainApp", []); mainApp.factory('MathService', function() { var factory = {}; factory.multiply = function(a, b) { return a * b } return factory; }); 使用服務(wù)方法
使用服務(wù)的方法,我們定義了一個(gè)服務(wù),然后分配方法。還注入已經(jīng)可用的服務(wù)。
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>結(jié)果
在Web瀏覽器打開(kāi)textAngularJS.html??吹浇Y(jié)果如下。

以上就是對(duì)AngularJS 服務(wù)的基礎(chǔ)資料整理,后續(xù)繼續(xù)整理相關(guān)資料,謝謝大家對(duì)本站的支持!
新聞熱點(diǎn)
疑難解答
圖片精選
網(wǎng)友關(guān)注