1

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

1 Answer 1

1

you could think about putting the $interval functionality in your controller so your service could be more generic/reusable.

Also $http returns a promise on it's own so you don't necessarily need to do that manually:

// your service 
.service('eedisplayService', function($http){
  this.getData = function(url) {
    return $http.get(url);
  }
}); 


// controller 
...
$interval(function() {
  eedisplayService.getData(...)
  .then(function(response) {
    // update the content in the view 
  })
}, 30000);
Sign up to request clarification or add additional context in comments.

1 Comment

Thanks so much for the answer!

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.