我有一個Angular應用程序,我正在顯示WP帳戶的帖子,我在服務中使用$scope
,但根據一些文章,將$scope
放入服務中不是一種正確的方式。
也有人問我做一個工廠,而不是。
我試圖不使用$scope
並創建一個工廠,但我的應用程序一旦我嘗試失敗。
這裏是一個Plunker我重新創建了我的應用程序的完整操作。代碼
而且這兒的一部分,你將在Plunker看到
.controller('NewsCtrl', function($scope,
FreshlyPressed, $stateParams) {
$scope.posts = [];
$scope.doRefresh = function() {
$scope.posts = FreshlyPressed.getBlogs($scope);
$scope.$broadcast('scroll.refreshComplete');
}
$scope.doRefresh();
})
.service('FreshlyPressed', function($http) {
return {
getBlogs: function($scope) {
$scope.postsURL = 'http://urbanetradio.com/wp-json/posts?_jsonp=JSON_CALLBACK';
$http.jsonp($scope.postsURL).success(function(data, status, headers, config) {
$scope.posts = data;
console.log(angular.toJson($scope.posts, 'pretty'));
}).error(function(data, status_headers, config) {
console.log('error')
});
},
getPostById: function(postId) {
var url ='http://urbanetradio.com/wp-json/posts/'+ postId;
return $http.get(url);
}
}
})
.controller('PostDetailCtrl', function($scope, $stateParams, $sce, FreshlyPressed) {
var postId = $stateParams.postId,
FreshlyPressed.getPostById(postId).success(function(response){
console.log(response);
$scope.post = response;
});
// Marks src as safe
$scope.trustSrc = function(src) {
return $sce.trustAsHtml(src);
};
});
所以你可以看到.service('FreshlyPressed')
,這是我想作爲一個工廠幹什麼用的,或者可能是相同的服務,但沒有的使用$scope
我應該如何在這裏設定承諾? – TheUnnamed
「設定承諾」是什麼意思? –