2014-07-24 54 views
0

我有一個jsonp調用服務器,返回一個包含兩個對象的對象。加載jsonp到多個anglarjs控制器

目前我使用jQuery進行jsonp調用,因爲我剛剛開始學習angularjs,我不知道它是如何完成的。

我想使用navControllerdata.filtersdata.resultscontentController

你會BEB與angularjs到aceive這個正確的方法是什麼?

(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

嗨請看這裏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(); 

});