angular.js - angular中可以在ng-click中直接調用service的方法嗎?
問題描述
代碼如下:
<!DOCTYPE html><html ng-app='myapp'><head> <meta charset='UTF-8'> <title>Angular學習</title></head><body><section ng-controller='Ctrl1 as ctrl1'><input type='text' ng-model='ctrl1.a'/><!-- 這里可以直接寫服務方法的調用嗎?原來的是ctrl1.setA() --><input type='button' value='設置' 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>
也就是說我不想用控制器的定義一個方法返回,而直接調用service里面的方法,可我試了不起作用,這是為什么呢?
問題解答
回答1:
首先$scope是ViewModel,即視圖層與模型層的橋梁。先看一下下圖:可以看出Ctrl1 as ctrl1語法,實際上是在$scope對象上新增一個ctrl1的屬性,而屬性值是一個包含setA和a屬性的對象。在創建Ctrl1的時候,我們只添加了setA屬性。為什么會有一個a屬性呢?因為你使用了ng-model指令(實現雙向綁定),當input輸入框改變時,發現ctrl1對象中沒有a屬性(綁定值是原始數據類型哈),那么它會自動創建一個。上面示例中Ctrl1的調整后的代碼如下:
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進行數據綁定時,推薦使用如下方式:
1.更新后模板
<section ng-controller='Ctrl1 as ctrl1'> <input type='text' ng-model='ctrl1.obj.a'/> <!-- ctrl1.obj.a 這個值推薦在Ctrl中直接獲取 --> <input type='button' value='設置' ng-click='ctrl1.setA(ctrl1.obj.a)'></section>
2.更新后Ctrl1
myapp.controller('Ctrl1',['MathService',function(MathService){ this.setA = MathService.setA; thi.obj = {};}]);
友情提示(已知的請略過):1.截圖中使用的調試工具是Chrome插件 - AngularJS2.示例中使用Angular stict DI,是推薦的做法。但如果嫌麻煩的話,可以參考使用gulp-ng-annotate
相關文章:
1. 數據庫 - mysql聯表去重查詢2. 用tp5框架寫sql語句3. 【python|scapy】sprintf輸出時raw_string轉string4. docker Toolbox在win10 家庭版中打開報錯5. mysql - 數據庫為什么需要鎖機制?6. python - 我已經連上了美國的VPN,而且在瀏覽器里查看的game排行也是美國的,可是為啥我用代碼怎么爬都是中國地區排行7. 就一臺服務器,mysql數據庫想實現自動備份,如何設計?8. mysql 能不能創建一個 有列級函數 的聯合視圖?9. python3.x - 關于Python圖遍歷的操作10. python小白 問關于參數無法找到的問題
