madimper
madimper

Reputation: 67

Angular.js refresh service inside a controller

i have a simple service inside a controller:

function OPctrl($scope, $http) {
    var s = 'http://query.yahooapis.com/v1/public/yql?q=select * from etc..... &format=json&callback=JSON_CALLBACK';
  $http.jsonp(s).success(function(data) {
      $scope.titoli = data.query.results.ROWSET.ROW;
  }).
  error(function(data, status, headers, config) {
    alert("error!")
    });
}   

The controller bind some data in a table. I need to recall and refresh data every time i need (i.e. with a refresh button). Can i work inside my controller ?How to ? Or i need a custom service? I am new to angular can anyone help?

Upvotes: 3

Views: 4001

Answers (1)

asgoth
asgoth

Reputation: 35829

It is better to use a custom service. To return the data to your controller, you have three possible options:

  • return a promise (using $q) and set the scope value in the promise then() function
  • add a callback to your service function and set the scope value within
  • let your service return an object instead of a primitive type and set it to a scope

To use your service you just inject it in your controller:

app.contoller('Ctrl', ['$scope', 'service', function($scope, service) {
...
}]);

All three possibilities can be seen in action is this jsFiddle.

Upvotes: 1

Related Questions