2016-08-19 18 views
0

我已經爲了使用其正常工作的API使用的控制器,但我想用工廠或服務來使用它,並曾嘗試這麼多時間,但可能是我沒有那麼多的理解。我目前正在爲AngularJs開設一門課程,所以如果我問一些愚蠢的話,我很抱歉。我已經使用控制器的JSON呼叫,但要使用工廠(angularjs)

而且這將是偉大誰能告訴我,什麼是最好使用廠家或服務或別的東西。

這樣,它工作得很好:

HTML:

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

控制器:

.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; 
    }); 
}]); 

這是我面臨的問題:

HTML:

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

控制器:

.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; 
    }); 
}]) 

廠:(我無法正常使用此,我認爲)

angular.module('confusionApp') 
    .factory('menuFactory', function() { 
     $http.get('http://www.zemtv.com/wp-json/wp/v2/posts').then(function(value) { 
      var posts = value.data; 
     }); 
}); 
+2

看看這個問題。它解釋了它all.http://stackoverflow.com/questions/15666048/angularjs-service-vs-provider-vs-factory – Manish

+0

在使用factrory? –

回答

0

我沒有測試過任何這一點,但它沿着線的:

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

然後從控制器:

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

這將是很好的更多讀什麼了對服務的使用,以及它們如何被注入並通過控制器使用。