成人在线亚洲_国产日韩视频一区二区三区_久久久国产精品_99国内精品久久久久久久

您的位置:首頁技術(shù)文章
文章詳情頁

angular.js - angular中可以在ng-click中直接調(diào)用service的方法嗎?

瀏覽:126日期:2024-09-15 18:15:00

問題描述

代碼如下:

<!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,即視圖層與模型層的橋梁。先看一下下圖:angular.js - angular中可以在ng-click中直接調(diào)用service的方法嗎?可以看出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)文章: