我对服务器进行了jsonp调用,该服务器返回一个包含两个对象的对象。
目前我使用jQuery调用jsonp,因为我刚刚开始学习AngularJS而且我不知道它是如何完成的。
我想在data.filters
使用navController
,data.results
使用contentController
使用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);
答案 0 :(得分: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();
});