国产探花免费观看_亚洲丰满少妇自慰呻吟_97日韩有码在线_资源在线日韩欧美_一区二区精品毛片,辰东完美世界有声小说,欢乐颂第一季,yy玄幻小说排行榜完本

首頁(yè) > 編程 > JavaScript > 正文

AngularJS 服務(wù)詳細(xì)講解及示例代碼

2019-11-20 09:13:10
字體:
來(lái)源:轉(zhuǎn)載
供稿:網(wǎng)友

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ì)本站的支持!

發(fā)表評(píng)論 共有條評(píng)論
用戶(hù)名: 密碼:
驗(yàn)證碼: 匿名發(fā)表
主站蜘蛛池模板: 洪湖市| 辽中县| 竹山县| 邢台市| 余庆县| 金川县| 通许县| 高淳县| 罗江县| 怀仁县| 江川县| 邻水| 长乐市| 大同县| 富平县| 江永县| 缙云县| 青海省| 体育| 锡林浩特市| 姚安县| 华亭县| 武定县| 洛川县| 无棣县| 浦江县| 长子县| 仪陇县| 曲靖市| 宜阳县| 阿勒泰市| 曲麻莱县| 淮滨县| 金川县| 拉萨市| 旬阳县| 子长县| 潢川县| 滦平县| 陕西省| 灵山县|