load jsonp into multiple AngularJS controllers

筅森魡賤 提交于 2019-12-25 00:52:50

问题


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:


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();

});


来源:https://stackoverflow.com/questions/24942678/load-jsonp-into-multiple-angularjs-controllers

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!