0

I have used a controller in order to use an api which works fine but I want to use it using factory or service and have tried this so many times but may be I don't have that much understanding of it. I am currently taking a course for AngularJs, so I am sorry if I am asking something stupid.

Also it would be great anyone can tell me that what would be best to use factory or service or something else.

This way it works fine:

HTML:

<div ng-controller="PromiseCtrl">
    <li ng-repeat="post in posts" >
        {{post.link}}<br/>
        {{post.title}}
    </li>
</div>

Controller:

.controller('PromiseCtrl', ['$scope', '$http', function($scope, $http) {
    $http.get('http://www.zemtv.com/wp-json/wp/v2/posts').then(function(value) {
        $scope.posts = value.data;
    });
}]);

This is where I am facing problem:

HTML:

<div ng-controller="PromiseCtrl">
    <li ng-repeat="post in posts" >
        {{post.link}}<br/>
        {{post.title}}
    </li>
</div>

Controller:

.controller('PromiseCtrl', ['$scope', '$http', function($scope, $http) {
    $http.get('http://www.zemtv.com/wp-json/wp/v2/posts').then(function(value) {
        $scope.posts = value.data;
    });
}])

Factory:(I am not using this correctly, I think)

angular.module('confusionApp')
    .factory('menuFactory', function() {
        $http.get('http://www.zemtv.com/wp-json/wp/v2/posts').then(function(value) {
            var posts = value.data;
        });
});
Immad Hamid
  • 789
  • 1
  • 8
  • 21

1 Answers1

0

I haven't tested any of this but it's along the lines of:

angular.module('confusionApp')
    .factory('menuFactory', function() {
        return { 
            getPosts: function () {
                return $http.get('http://www.zemtv.com/wp-json/wp/v2/posts')
            }
        }
});

Then from the controller:

.controller('PromiseCtrl', ['$scope', '$http', 'menuFactory', function($scope, $http, menuFactory) {
    menuFactory.getPosts().then(function(response){
       $scope.posts = response.data;
    });
}]);

It would be good to read what up more on the uses of services and how they are injected and used by controllers.

georgeawg
  • 48,608
  • 13
  • 72
  • 95
cullimorer
  • 755
  • 1
  • 5
  • 23