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. 为什么span的color非要内联样式才起作用?2. javascript - swiper.js嵌套了swiper 初始设置不能向下一个滑动 结束后重新初始3. python - Django ManyToManyField 字段数据在 admin后台 显示不正确,这是怎么回事?4. docker - 如何修改运行中容器的配置5. python - 如何修改twisted自带的日志输出格式?6. 求救一下,用新版的phpstudy,数据库过段时间会消失是什么情况?7. 请问一下各位老鸟 我一直在学习独孤九贱 现在是在tp5 今天发现 这个系列视频没有实战8. 在cmd下进入mysql数据库,可以输入中文,但是查看表信息,不显示中文,是怎么回事,怎新手,请老师9. 如何使用git对word文档进行版本控制?10. 高并发写入和更新mysql

网公网安备