AngularJS支持使用服務的體系結構“關注點分離”的概念。服務是JavaScript函數,并負責只做一個特定的任務。這也使得他們即維護和測試的單獨實體。控制器,過濾器可以調用它們作為需求的基礎。服務使用AngularJS的依賴注入機制注入正常。
AngularJS提供例如許多內在的服務,如:$http, $route, $window, $location等。每個服務負責例如一個特定的任務,$http是用來創建AJAX調用,以獲得服務器的數據。 $route用來定義路由信息等。內置的服務總是前綴$符號。
有兩種方法來創建服務。
工廠
服務
使用工廠方法
使用工廠方法,我們先定義一個工廠,然后分配方法給它。
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 服務的基礎資料整理,后續繼續整理相關資料,謝謝大家對本站的支持!
新聞熱點
疑難解答