from :
http://programer-learn.blogspot.tw/2014/07/angularjs-service.html
-Service 可以把它想做是一個提供某一項服務的物件
-Service 封裝了某一個定功能的實作邏輯,讓你能夠在不同模組之間重覆使用(reuse)
-AngularJS 的 Module 提供了三個方法(method)來定義你的 Service , 分別是 factory、service 以及 provider
這三個方法的結果完全是一樣的,就是一個 Service Object (注意:是一個物件)
而這三種方法的差別其實僅在於 Service Object 的建立與管理的過程
<!doctype html>
<html lang="en">
<head>
<meta charset="UTF-8">
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.4.0/angular.min.js"></script>
<script src="js.js"></script>
<title>Examples</title>
<script>
var demoApp = angular.module("demoApp", []);
demoApp.controller("demoCtrl1", function($scope, echoService){
$scope.name = "Allen";
$scope.echo = function(){
alert("demoCtrl1");
echoService.echo($scope.name);
};
}).controller("demoCtrl2", function($scope, echoService){
$scope.name = "Bob";
$scope.echo = function(){
alert("demoCtrl2");
echoService.echo($scope.name);
};
});
demoApp.factory("echoService", function(){
console.log("Factory Function be executed...");
var echoCount = 0;
return {
echo: function(name){
return console.log((echoCount++) + ", Your name is " + name);
}
};
});
</script>
</head>
<body ng-app="demoApp">
<div ng-controller="demoCtrl1">
Name : <input type="text" ng-model="name"/><br/>
<button ng-click="echo()">click</button>
</div>
<div ng-controller="demoCtrl2">
Name : <input type="text" ng-model="name"/><br/>
<button ng-click="echo()">click</button>
</div>
</body>
</html>
沒有留言:
張貼留言