使 html 上无法访问 $scope 的服务
Service making the $scope not accessible on the html
无法访问范围,例如将 {{ pagec }}
放在 html 上不起作用,但是当我从控制器中删除 blogpostservice
时它再次正常工作。
var app = angular.module('Blog', []);
app.factory('blogpostservice', ['$http', function ($http) {
this.getMoreData = function (pagecount) {
return $http.get('/api/posts/' + pagecount);
}
}]);
app.controller('MainController', ['$scope', 'blogpostservice',
function ($scope, blogpostservice) {
$scope.pagec = 1;
$scope.posts = [];
this.getMoreData = function (posts) {
blogpostservice.getMoreData(pagec).success(function () {
alert('got it successfully!!!');
}).error(function () {
alert('something went wrong!!!');
});
}
}]);
因为你有错误的 factory
实现,factory
应该总是 return 和 object
。您一定是控制台出错了(请检查)。
app.factory('blogpostservice', ['$http',
function ($http) {
function getMoreData (pagecount) {
return $http.get('/api/posts/' + pagecount);
}
return {
getMoreData: getMoreData
}
}
]);
或者您可以将 factory
转换为 service
,您需要像之前那样将数据绑定到 this
(上下文)。
app.service('blogpostservice', ['$http', function ($http) {
this.getMoreData = function (pagecount) {
return $http.get('/api/posts/' + pagecount);
}
}]);
Also don't use .success
/.error
on $http
call, they are
deprecated. Instead use .then
.
无法访问范围,例如将 {{ pagec }}
放在 html 上不起作用,但是当我从控制器中删除 blogpostservice
时它再次正常工作。
var app = angular.module('Blog', []);
app.factory('blogpostservice', ['$http', function ($http) {
this.getMoreData = function (pagecount) {
return $http.get('/api/posts/' + pagecount);
}
}]);
app.controller('MainController', ['$scope', 'blogpostservice',
function ($scope, blogpostservice) {
$scope.pagec = 1;
$scope.posts = [];
this.getMoreData = function (posts) {
blogpostservice.getMoreData(pagec).success(function () {
alert('got it successfully!!!');
}).error(function () {
alert('something went wrong!!!');
});
}
}]);
因为你有错误的 factory
实现,factory
应该总是 return 和 object
。您一定是控制台出错了(请检查)。
app.factory('blogpostservice', ['$http',
function ($http) {
function getMoreData (pagecount) {
return $http.get('/api/posts/' + pagecount);
}
return {
getMoreData: getMoreData
}
}
]);
或者您可以将 factory
转换为 service
,您需要像之前那样将数据绑定到 this
(上下文)。
app.service('blogpostservice', ['$http', function ($http) {
this.getMoreData = function (pagecount) {
return $http.get('/api/posts/' + pagecount);
}
}]);
Also don't use
.success
/.error
on$http
call, they are deprecated. Instead use.then
.