您的位置:首页技术文章
文章详情页

angular.js - angular中可以在ng-click中直接调用service的方法吗?

【字号: 日期:2024-09-15 18:15:00浏览:28作者:猪猪

问题描述

代码如下:

<!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,即视图层与模型层的桥梁。先看一下下图:angular.js - angular中可以在ng-click中直接调用service的方法吗?可以看出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

相关文章: