3

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?

1 Answer 1

1

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.

Sign up to request clarification or add additional context in comments.

4 Comments

Thx, i know this fiddle already. Is a very complex example for a newbie like me.
Sorry about that. It is complex because it shows the 3 types, which causes quite some coding.
If possible, i need a more straightforward tutorial. For now i can't figure out the rules about events and controllers in an angular application.
Then I suggest you start here. There are also some interesting YouTube screencasts.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.