javascript - angular里的$interval是不是不能写到service中?

查看:68
本文介绍了javascript - angular里的$interval是不是不能写到service中?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

问 题

起始是这样的,没毛病

angular.module('myApp',['ionic','ctrlController','serviceModule'])

此处控制器
angular.module('serviceModule',[])
.controller('myIndianaCtrl',function($scope,Timer){
    Timer.timer(function(a,b,c){
            $scope.h=a;
            $scope.m=b;
            $scope.s=c;
        })
 })

此处服务
angular.module('serviceModule',[])
.service('Timer',[function($interval){
    var _this=this;
    this.timer=function(callbackFun){
        var h=23,m=23,s=59;
        _this.h=h;
        _this.m=m;
        _this.s=s;
        callbackFun(_this.h,_this.m,_this.s);
        return this;
    }
}])

以上代码在view里绑定的话, 可以显示 h m s,然而当我想加个倒计时,例如这样

angular.module('serviceModule',[])
.service('Timer',[function($interval){
    var _this=this;
    this.timer=function(callbackFun){
        var h=23,m=23,s=59;
        $interval(function run(){
            --s;
                if(s<0){
                    --m;
                    s=59;
                }
                if(m<0){
                    --h;
                    m=59;
                }
                if(h<0){
                    h=00;
                    m=00;
                    s=00;
                }
                _this.h=h;
                _this.m=m;
                _this.s=s;
            callbackFun(_this.h,_this.m,_this.s);
        })

        return this;
    }
}])

这时console里面会报这样子的错误,然后就没有然后了,不晓得咋整了

是interval不能写到service里面的吗?
如果能,求大神举个小栗子就好,拜谢!

解决方案

你这是应该是注入被混淆了的毛病

这么写试试

angular.module('serviceModule',[])
.service('Timer',['$interval', function($interval){
// ...

这篇关于javascript - angular里的$interval是不是不能写到service中?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆