代碼如下:
<!DOCTYPE html>
<html lang="en" ng-app="myapp">
<head>
<meta charset="UTF-8">
<title>Angular學(xué)習(xí)</title>
<style type="text/css">
section{
border-bottom:1px dashed #333;
padding:50px;
}
</style>
</head>
<body>
<section ng-controller="Ctrl1 as ctrl1">
<input type="text" ng-model="ctrl1.a"/>
<!-- 這里可以直接寫(xiě)服務(wù)方法的調(diào)用嗎?原來(lái)的是ctrl1.setA() -->
<input type="button" value="設(shè)置" ng-click="MathService.setA(ctrl1.a)">
</section>
<section ng-controller="Ctrl2 as ctrl2">
<h1>{{ctrl2.getA()}}</h1>
</section>
<script type="text/javascript" src="js/lib/angular/angular.min.js"></script>
<script type="text/javascript">
var myapp = angular.module("myapp",[]);
myapp.controller("Ctrl1",["MathService",function(MathService){
this.set = function(){
return MathService.setA(this.a);
}
}]);
myapp.controller("Ctrl2",["MathService",function(MathService){
this.getA = function(){
return MathService.getA();
}
}]);
myapp.service("MathService",[function(){
var a = 999;
this.getA = function(){
return a;
}
this.setA = function(number){
a = number;
}
}]);
</script>
</body>
</html>
也就是說(shuō)我不想用控制器的定義一個(gè)方法返回,而直接調(diào)用service里面的方法,可我試了不起作用,這是為什么呢?
首先$scope是ViewModel,即視圖層與模型層的橋梁。先看一下下圖:
可以看出Ctrl1 as ctrl1語(yǔ)法,實(shí)際上是在$scope對(duì)象上新增一個(gè)ctrl1的屬性,而屬性值是一個(gè)包含setA和a屬性的對(duì)象。在創(chuàng)建Ctrl1的時(shí)候,我們只添加了setA屬性。為什么會(huì)有一個(gè)a屬性呢?因?yàn)槟闶褂昧薾g-model指令(實(shí)現(xiàn)雙向綁定),當(dāng)input輸入框改變時(shí),發(fā)現(xiàn)ctrl1對(duì)象中沒(méi)有a屬性(綁定值是原始數(shù)據(jù)類型哈),那么它會(huì)自動(dòng)創(chuàng)建一個(gè)。上面示例中Ctrl1的調(diào)整后的代碼如下:
myapp.controller("Ctrl1",["MathService",function(MathService){
this.setA = MathService.setA;
}]);
模板中直接使用的service的話,可以把service添加到$rootScope對(duì)象上:
var myapp = angular.module("myapp",[]).run(["$rootScope",
"MathService", function($rootScope, MathService) {
return $rootScope.mathService = MathService;}
]);
個(gè)人不推薦這樣使用,如果使用這樣方法,最好加個(gè)命名空間。
另外使用ng-model進(jìn)行數(shù)據(jù)綁定時(shí),推薦使用如下方式:
1.更新后模板
<section ng-controller="Ctrl1 as ctrl1">
<input type="text" ng-model="ctrl1.obj.a"/>
<!-- ctrl1.obj.a 這個(gè)值推薦在Ctrl中直接獲取 -->
<input type="button" value="設(shè)置" ng-click="ctrl1.setA(ctrl1.obj.a)">
</section>
2.更新后Ctrl1
myapp.controller("Ctrl1",["MathService",function(MathService){
this.setA = MathService.setA;
thi.obj = {};
}]);
友情提示(已知的請(qǐng)略過(guò)):
1.截圖中使用的調(diào)試工具是Chrome插件 - AngularJS
2.示例中使用Angular stict DI,是推薦的做法。但如果嫌麻煩的話,可以參考使用
gulp-ng-annotate