我有一个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
“设定承诺”是什么意思? –