user3930160
user3930160

Reputation: 1

Angular - function inside .factory

I'm trying to run a function inside .factory to get posts, but I get an undefined error on my controller.

.factory('Portfolio', function($http, $log) {
  //get jsonp
    this.getPosts = function($scope) {
        $http.jsonp("http://test.uxco.co/json-test.php?callback=JSON_CALLBACK")
            .success(function(result) {
                $scope.posts = $scope.posts.concat(result);
                $scope.$broadcast("scroll.infiniteScrollComplete");
            });
    };
});


.controller('PortfolioCtrl', function($scope, Portfolio) {
    $scope.posts = [];
    Portfolio.getPosts($scope);

Thanks!

Upvotes: 0

Views: 834

Answers (2)

ebram khalil
ebram khalil

Reputation: 8321

What you wrote is a service not a factory. so you either

  • change it to be .service instead of .factory.
  • or return the function inside an object like this
.factory('Portfolio', function($http, $log) {
    //get jsonp
    return {
        getPosts: function($scope) {
            $http.jsonp()
                .success(function(result) {
                    $scope.posts = $scope.posts.concat(result);
                    $scope.$broadcast("scroll.infiniteScrollComplete");
                });
        };
    }

});

check the difference between service and factory

Upvotes: 1

Rajesh Manilal
Rajesh Manilal

Reputation: 1124

Use .factory code like this

.factory('Portfolio', function($http, $log) {
  //get jsonp
   return{
       getPosts: function($scope) {
        $http.jsonp("http://test.uxco.co/json-test.php?callback=JSON_CALLBACK")
        .success(function(result) {
            $scope.posts = $scope.posts.concat(result);
            $scope.$broadcast("scroll.infiniteScrollComplete");
        });
      };
    }
});

Upvotes: 0

Related Questions