angular js一factory,service,provider创建服务
生活随笔
收集整理的這篇文章主要介紹了
angular js一factory,service,provider创建服务
小編覺(jué)得挺不錯(cuò)的,現(xiàn)在分享給大家,幫大家做個(gè)參考.
服務(wù):在AngularJS 中,服務(wù)是一個(gè)函數(shù)或?qū)ο?/span>
在寫控制器的時(shí)候,不要復(fù)用controller,當(dāng)我們的controller里面有相同的代碼時(shí),此時(shí)需要把它抽取成一個(gè)服務(wù),所有的服務(wù)都符合依賴注入的原則,服務(wù)在整個(gè)應(yīng)用的生命周期中存在,可用來(lái)共享數(shù)據(jù)。
Angular提供了3種方法來(lái)創(chuàng)建服務(wù),factory,service,provider
<!DOCTYPE html> <html> <head><meta charset="utf-8"/> </head> <body> <div ng-app="myApp" ng-controller="myCtrl"><input type="text" ng-model="name"/> {{name}} </div> <script src="http://cdn.static.runoob.com/libs/angular.js/1.4.6/angular.min.js"></script> <script>var app=angular.module("myApp",[]);//自定義服務(wù)provider,myService1為服務(wù)名app.provider('myService1', function () {this.$get = function () {return{message: 'customprovider Message'}}});//自定義服務(wù)serviceapp.service('myService2', function () {return ['上海'];});//自定義工廠factoryapp.factory("myService3", [function () {return [1, 2, 3, 4, 5, 6];}]);//service和factory類似,但返回的東西必須是對(duì)象
app.controller('myCtrl',function($scope,myService1,myService2,myService3){$scope.name = '橘子';console.log(myService1);console.log(myService2);console.log(myService3);}); </script> </body> </html>
效果截圖
共享數(shù)據(jù)
<!DOCTYPE html> <html> <head><meta charset="utf-8"/> </head> <body> <div ng-app="myApp"><div ng-controller="firstCtrl"><input type="text" ng-model="data.name"/><input type="text" ng-model="Data.message"/><p>first{{data.name}}</p><p>first{{Data.message}}</p></div><div ng-controller="secondCtrl"><p>second{{data.name}}</p><p>second{{Data.message}}</p></div> </div> <script src="http://cdn.static.runoob.com/libs/angular.js/1.4.6/angular.min.js"></script> <script>var app = angular.module("myApp",[]);app.factory('Data',function(){return{message:'共享的數(shù)據(jù)'}});app.controller('firstCtrl',function($scope,Data){$scope.data ={name: '橘子'};$scope.Data = Data;});app.controller('secondCtrl',function($scope,Data){$scope.Data = Data;}); </script> </body> </html>?
轉(zhuǎn)載于:https://www.cnblogs.com/Tiboo/p/6757530.html
與50位技術(shù)專家面對(duì)面20年技術(shù)見(jiàn)證,附贈(zèng)技術(shù)全景圖總結(jié)
以上是生活随笔為你收集整理的angular js一factory,service,provider创建服务的全部?jī)?nèi)容,希望文章能夠幫你解決所遇到的問(wèn)題。
- 上一篇: React.js核心原理实现:首次渲染机
- 下一篇: CCF NOI1054 扫雷游戏