javascript - angular里的$interval是不是不能写到service中?
PHP中文网
PHP中文网 2017-04-11 10:28:45
[JavaScript讨论组]

起始是这样的,没毛病

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里面的吗?
如果能,求大神举个小栗子就好,拜谢!

PHP中文网
PHP中文网

认证0级讲师

全部回复(1)
PHPz

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

这么写试试

angular.module('serviceModule',[])
.service('Timer',['$interval', function($interval){
// ...
热门教程
更多>
最新下载
更多>
网站特效
网站源码
网站素材
前端模板
关于我们 免责申明 举报中心 意见反馈 讲师合作 广告合作 最新更新 English
php中文网:公益在线php培训,帮助PHP学习者快速成长!
关注服务号 技术交流群
PHP中文网订阅号
每天精选资源文章推送
PHP中文网APP
随时随地碎片化学习

Copyright 2014-2025 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号