很抱歉,如果这似乎是一个菜鸟问题,但这是因为我是一个菜鸟。我一直在研究,找不到答案。我试着弄清楚自己,但我最终搞砸了更多东西。
我有一个控制器从JSON URL获取数据。问题是我想要另一个控制器(使用相同的API / JSON),但它有一个稍微不同的URL,相同的服务器。
下面是正在运行的代码,因此我只需要调整/复制它以从URL添加/ podcast /
中获取JSON数据angular.module('myapp')
.controller('PostsCtrl', function($scope, $http, DataLoader, $timeout, $ionicSlideBoxDelegate, $rootScope) {
$rootScope.url = 'http://genesis2media.com/mobile/wp-json/wp/v2/';
console.log('PostsCtrl');
$scope.loadPosts = function() {
DataLoader.get($rootScope.url + 'posts').then(function(response) {
$scope.posts = response.data;
console.log(response.data);
}, function(response) {
console.log('error', response);
});
}
// Load posts on page load
$scope.loadPosts();
paged = 2;
$scope.moreItems = true;
// Load more (infinite scroll)
$scope.loadMore = function() {
if (!$scope.moreItems) {
return;
}
var pg = paged++;
$timeout(function() {
DataLoader.get($rootScope.url + 'posts' + '?page=' + pg).then(function(response) {
angular.forEach(response.data, function(value, key) {
$scope.posts.push(value);
});
if (response.data.length <= 0) {
$scope.moreItems = false;
}
}, function(response) {
$scope.moreItems = false;
console.log('error');
});
$scope.$broadcast('scroll.infiniteScrollComplete');
$scope.$broadcast('scroll.resize');
}, 1000);
}
$scope.moreDataExists = function() {
return $scope.moreItems;
}
// Pull to refresh
$scope.doRefresh = function() {
console.log('Refreshing!');
$timeout(function() {
$scope.loadPosts();
//Stop the ion-refresher from spinning
$scope.$broadcast('scroll.refreshComplete');
}, 1000);
};
})
.controller('PostCtrl', function($scope, $stateParams, DataLoader, $ionicLoading, $rootScope, $sce) {
$ionicLoading.show({
noBackdrop: true
});
var singlePostApi = $rootScope.url + 'posts/' + $stateParams.postId;
DataLoader.get(singlePostApi).then(function(response) {
$scope.post = response.data;
// Don't strip post html
$scope.content = $sce.trustAsHtml(response.data.content.rendered);
$ionicLoading.hide();
}, function(response) {
console.log('error', response);
});
});
答案 0 :(得分:0)
希望这就是你要找的东西,
共享服务示例
var app = angular.module('project',[]);
app.factory('sharedService', function($http) {
return {
method:functon() {
// do your stuff $http.get/post
// return data
}
};
});
function FirstCtrl($scope, sharedService) {
$scope.data= sharedService.method();
}
function SecondCtrl($scope, sharedService) {
$scope.data= sharedService.method();
}