<!DOCTYPE HTML>
<html lang="zh-cn" ng-app="MainApp">
<head>
<meta charset="UTF-8">
<title>explicit-inject-service</title>
</head>
<body>
<div ng-controller="MyController">
<input type="text" ng-model="msg"/>
<button ng-click="saveMsg()">save msg</button>
<ul>
<li ng-repeat="msg in msgs">{{msg}}</li>
</ul>
</div>>
<script src="js/angular.js" type="text/javascript"></script>
<script type="text/javascript">
var app = angular.module("MainApp",[],function($provide) {
$provide.factory("notify",["$window","$timeout",function(win,timeout) {
//这里是服务依赖服务,通过这种显式的方式,参数名可以乱填,但顺序要对应
var msgs = [];
return function(msg) {
msgs.push(msg);
if(msgs.length==3) {
timeout(function() {
win.alert(msgs.join("\n"));
msgs = [];
},10);
}
}
}]);
}); function MyController($s,$noti) {
//这里是controller依赖服务,通过这种显式的方式,参数名可以乱填,但顺序要对应
$s.msgs = [];
$s.saveMsg = function() {
this.msgs.push(this.msg);
$noti(this.msg);
this.msg = "";
};
} //这个就是让controller里面的$s指向$scope,$noti指向notify这个服务
MyController.$inject = ['$scope','notify'];
//有显示依赖和隐示依赖
</script>
</body>
</html>