Monday, February 1, 2016

Angular: factory example with http request

Angular factory using http request with an argument.

<div ng-app="AppName" ng-controller="OneController">
    {{response}}
</div>
 
<script src="http://code.angularjs.org/1.2.14/angular.min.js"></script>
<script>
angular.module('AppName', []);
    
angular.module('AppName').factory('githubService', ['$http', function($http) {
 
    var doRequest = function(keyword) {
      return $http({
        method: 'GET',
        url: 'https://api.github.com/users/' + keyword + '/events'
      });
    }
    return function(keyword) { return doRequest(keyword); };
}]);
 
angular.module('AppName').controller('OneController', ['$scope', 'githubService', function($scope, githubService) {
    
    githubService('google').then(
        function(data) { 
            $scope.response = data.data; 
        }, 
        function(error){ 
            $scope.response = 'error';
        }
    );

}]);
</script>

No comments:

Post a Comment