Processing $http response in service

How to use AngularJS promises to update the model from an asyncronous service.

by bruscopelliti

HTML

<script src="http://getfirebug.com/releases/lite/1.2/firebug-lite-compressed.js"></script>
<!doctype html>
<html lang="en" ng-app="myApp">
    
    <head>
        <meta charset="utf-8" />
        <title>My AngularJS App</title>
    </head>
    
    <body ng-controller="stageController">
        	<h1>Feed:</h1>

        <ul>
            <li ng-repeat="feed in feeds"> <a ng-href="{{feed.source}}">{{feed.title}}</a>
 <span class="date">{{feed.date}}</span>

            </li>
        </ul>
    </body>

</html>

CSS

</style> <!-- Ugly Hack due to jsFiddle issue: http://goo.gl/BUfGZ --> <script src="http://ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script> <script src="http://ajax.googleapis.com/ajax/libs/angularjs/1.0.5/angular.min.js"></script> <style>

JavaScript

'use strict';

		// Declare app level module which depends on filters, and services
		angular.module('myApp', ['myApp.services']);

		/* Controllers */
		function stageController(scope, f) {
		    scope.feeds = [];
            
            /* real case:
            * This won't work on jsfiddle
            */
		    f.getFeedReal().then(function (d) {
		        console.dir(d);
		        scope.feeds = d.data;
		    });
		}
		stageController.$inject = ['$scope', 'feedSrv'];

		angular.module('myApp.services', []).
		factory('feedSrv', ['$http', function (async) {
		    return {
		        getFeedReal: function () {
		            var promise = async({
		                method: 'GET',
		                url: 'getFeed.php'
		            }).
		            success(function (data, status, headers, config) {
		                return data;
		            }).
		            error(function (data, status, headers, config) {
		                return {
		                    "status": false
		                };
		            });
		            return promise;
		        }
		    }
		}]);