[{
"id" : 1,
"name": "Ben"
},
{
"id" : 2,
"name": "Jessie"
},
{
"id" : 3,
"name": "Laney"
},
{
"id" : 4,
"name": "Lincoln"
}]
var app = angular.module('angularjs-starter', []);
app.controller('MainCtrl', function($scope, myService) {
//The clean way
$scope.foo = myService.getFoo();
//The "but I really like callbacks" way.
myService.getFoo().then(function(data) {
$scope.foo2 = data;
});
//The "common callback" pattern
myService.getBar(function(data) {
$scope.bar = data;
});
//So what happens if I just return
// whatever $http.get() returns?
$scope.test = myService.testHttpGetResult();
});
app.factory('myService', function($http, $q) {
return {
getFoo: function() {
var deferred = $q.defer();
$http.get('foo.json').success(function(data) {
deferred.resolve(data);
}).error(function(){
deferred.reject();
});
return deferred.promise;
},
getBar: function(callback) {
$http.get('foo.json').success(callback);
},
testHttpGetResult: function (){
return $http.get('foo.json');
}
}
});
<!DOCTYPE html>
<html ng-app="angularjs-starter">
<head lang="en">
<meta charset="utf-8">
<title>Custom Plunker</title>
<script src="//ajax.googleapis.com/ajax/libs/angularjs/1.0.3/angular.min.js"></script>
<link rel="stylesheet" href="style.css">
<script>
document.write('<base href="' + document.location + '" />');
</script>
<script src="app.js"></script>
</head>
<body ng-controller="MainCtrl">
<h3>$scope.foo</h3>
<ul>
<li ng-repeat="item in foo">{{item.id}} - {{item.name}}</li>
</ul>
<h3>$scope.foo2</h3>
<ul>
<li ng-repeat="item in foo2">{{item.id}} - {{item.name}}</li>
</ul>
<h3>$scope.bar</h3>
<ul>
<li ng-repeat="item in bar">{{item.id}} - {{item.name}}</li>
</ul>
<br/>
<h3>And here is what you get if you just return the promise returned by $http.get():</h3>
<pre>{{test | json}}</pre>
</body>
</html>
/* CSS goes here */