Skip to content

Instantly share code, notes, and snippets.

@fmtarif
Last active August 29, 2015 14:06
Show Gist options
  • Save fmtarif/5af129dd9a0488b9b80d to your computer and use it in GitHub Desktop.
Save fmtarif/5af129dd9a0488b9b80d to your computer and use it in GitHub Desktop.
#ng angular mock backend using $httpBackend
<!doctype html>
<html>
<head>
<script src="//cdnjs.cloudflare.com/ajax/libs/angular.js/1.2.20/angular.js"></script>
<script src="//cdnjs.cloudflare.com/ajax/libs/angular.js/1.2.20/angular-mocks.js"></script>
<script>
var app = angular.module("app", ['ngMockE2E']);
//mock data for backend to respond with
var posts = [
{id:"1", title:"post title 1"}
,{id:"2", title:"post title 2"}
,{id:"3", title:"post title 3"}
];
//define your mock backend endpoints
app.run(function($httpBackend) {
$httpBackend.whenGET('/posts').respond(function(method, url, data, headers) {
return [200, posts, {/*headers*/}];
});
});
//global delay for all backend responses
app.config(function($provide) {
var milliSeconds = 3000;
$provide.decorator('$httpBackend', function($delegate) {
var proxy = function(method, url, data, callback, headers) {
var interceptor = function() {
var _this = this,
_arguments = arguments;
setTimeout(function() {
callback.apply(_this, _arguments);
}, milliSeconds);
};
return $delegate.call(this, method, url, data, interceptor, headers);
};
for(var key in $delegate) {
proxy[key] = $delegate[key];
}
return proxy;
});
});
app.controller('Ctrl', function($scope, $http) {
$scope.loading = true;
$http.get('/posts').success(function(data, status) { //end point will be handled by $httpBackend
$scope.loading = false;
$scope.posts = data;
});
});
</script>
</head>
<body ng-app="app" ng-controller="Ctrl" >
<div data-ng-init="angular='angular working!'">{{angular}}</div>
<p data-ng-show="loading">Loading posts.....</p>
<ul>
<li data-ng-repeat="post in posts">
<span>{{ post.title }}</span>
</li>
</ul>
</body>
</html>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment