angular.js - angular中可以在ng-click中直接調(diào)用service的方法嗎?
問題描述
代碼如下:
<!DOCTYPE html><html ng-app='myapp'><head> <meta charset='UTF-8'> <title>Angular學(xué)習(xí)</title></head><body><section ng-controller='Ctrl1 as ctrl1'><input type='text' ng-model='ctrl1.a'/><!-- 這里可以直接寫服務(wù)方法的調(diào)用嗎?原來的是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'>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>
也就是說我不想用控制器的定義一個方法返回,而直接調(diào)用service里面的方法,可我試了不起作用,這是為什么呢?
問題解答
回答1:
首先$scope是ViewModel,即視圖層與模型層的橋梁。先看一下下圖:可以看出Ctrl1 as ctrl1語法,實際上是在$scope對象上新增一個ctrl1的屬性,而屬性值是一個包含setA和a屬性的對象。在創(chuàng)建Ctrl1的時候,我們只添加了setA屬性。為什么會有一個a屬性呢?因為你使用了ng-model指令(實現(xiàn)雙向綁定),當(dāng)input輸入框改變時,發(fā)現(xiàn)ctrl1對象中沒有a屬性(綁定值是原始數(shù)據(jù)類型哈),那么它會自動創(chuàng)建一個。上面示例中Ctrl1的調(diào)整后的代碼如下:
myapp.controller('Ctrl1',['MathService',function(MathService){ this.setA = MathService.setA;}]);
模板中直接使用的service的話,可以把service添加到$rootScope對象上:
var myapp = angular.module('myapp',[]).run(['$rootScope', 'MathService', function($rootScope, MathService) { return $rootScope.mathService = MathService;}]);
個人不推薦這樣使用,如果使用這樣方法,最好加個命名空間。
另外使用ng-model進(jìn)行數(shù)據(jù)綁定時,推薦使用如下方式:
1.更新后模板
<section ng-controller='Ctrl1 as ctrl1'> <input type='text' ng-model='ctrl1.obj.a'/> <!-- ctrl1.obj.a 這個值推薦在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 = {};}]);
友情提示(已知的請略過):1.截圖中使用的調(diào)試工具是Chrome插件 - AngularJS2.示例中使用Angular stict DI,是推薦的做法。但如果嫌麻煩的話,可以參考使用gulp-ng-annotate
相關(guān)文章:
1. angular.js - angularjs的自定義過濾器如何給文字加顏色?2. angular.js - angular內(nèi)容過長展開收起效果3. 關(guān)于docker下的nginx壓力測試4. docker鏡像push報錯5. 關(guān)于nginx location配置的問題,root到底是什么6. linux - openSUSE 上,如何使用 QQ?7. 并發(fā)模型 - python將進(jìn)程池放在裝飾器里為什么不生效也沒報錯8. 大家好,請問在python腳本中怎么用virtualenv激活指定的環(huán)境?9. python的前景到底有大?如果不考慮數(shù)據(jù)挖掘,機(jī)器學(xué)習(xí)這塊?10. linux - 升級到Python3.6后GDB無法正常運行?
