Taha Mouhtij Taha Mouhtij - 1 month ago 11
AngularJS Question

Service making the $scope not accessible on the html

Can't access the scope, for example putting

{{ pagec }}
on the html isn't working but when I remove
blogpostservice
from the controller it works fine again.

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!!!');
});
}


}]);

Answer Source

Because you had wrong factory implementation, factory should always return an object. You must have got an error in console(please check).

app.factory('blogpostservice', ['$http', 
  function ($http) {
    function getMoreData (pagecount) {
        return $http.get('/api/posts/' + pagecount);
    }
    return {
       getMoreData: getMoreData
    }
  }
]);

Or you can convert your factory to service, there you need to bind data to this(context) like your were doing before.

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.