0

I have a jsonp call to a server which returns an object containing two objects.

At the moment I make the jsonp call with jQuery because I've just started learning AngularJS and I dont know how it's done.

I want to use data.filters in navController and data.results in contentController

What would be the correct way to achieve this with AngularJS ?

(function($, angular) {
    $(function() {
        $.ajax({
            jsonp: "JSONPCallback",
            url: 'myUrl',
            dataType: 'jsonp',
            success: function(data) {
               //data =  {"filters":{...},"results":{...}}
            }
        });
     });

     var app = angular.module('app', []);
     var controllers = {};

     controllers.navController = function($scope) {
          $scope.filters = [{}];
     };

      controllers.contentController = function($scope) {
          $scope.results = [{}];
     };

     app.controller(controllers);

})(jQuery, angular);

1 Answer 1

1

Hi please see here http://plnkr.co/edit/hYkkQ6WctjhYs8w7I8sT?p=preview

var app = angular.module('plunker', []);


app.service('dataService', function($http){

  var url = "http://public-api.wordpress.com/rest/v1/sites/wtmpeachtest.wordpress.com/posts?callback=JSON_CALLBACK";

  var dataReady= false
  var filters = [];
  var results = [];

  function getData() {

    if (dataReady)
    retrun
    else
    {

      $http.jsonp(url)
    .success(function(data){

        //in your case 
        //angular.copy(data.filters, filters)
        //angular.copy(data.results , results )
        angular.copy(data.posts[0], results);
        angular.copy(data.posts[1], filters);
        dataReady = true
    }).error(function(){

      alert('cant load data');

    });

    }


  }


  return {
    filters : filters,
    results : results,
    getData : getData
  }

})
app.controller('MainCtrl', function($scope,dataService) {
  $scope.name = 'World';

  $scope.items = dataService.results;

  dataService.getData();

});

app.controller('SecondCtrl', function($scope,dataService) {


  $scope.filters = dataService.filters;

  dataService.getData();

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

Comments

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.