AngularJs $ interval服务

I'm a beginner in Angularjs and so I would like ask you if there is a better way for solve my issue.

I need to update, for example, every 30 seconds the content of a <div> with an ajax call.

HTML

<div>
    <div>{{test.value}}</div>
</div>

My idea was use $interval on a service as following:

.service('eedisplayService', function($q, $http, $interval){
    this.getData = function(url, variable){
        $interval(function (){
            var deferred = $q.defer();
             $http.get(url)
            .success(function(data){
                if (data){
                    variable.value = data
                } else {
                    deferred.reject('Wrong response');
                }
            })
            .error(function(){
                deferred.reject();
            });
            return deferred.promise
        },30000);
    }

});

And call service from controller like this:

.controller('displayCtrl', function($scope, config, eedisplayService){

    var url = "myUrl";

    $scope.test = {value : "" };

    eedisplayService.getData(url, $scope.test);

});

Is it a fully AngularJs approach? The code works, but is a good choice call a service with an $interval from controller? Is not better call it from config for example?

I checked out a lot of examples, but I don't really understand what is the best way to do this.

Thanks so much.

Regards

查看全部
weixin_33729196
weixin_33729196
2016/02/11 19:02
  • angularjs
  • ajax
  • javascript
  • 点赞
  • 收藏
  • 回答
    私信

1个回复