Skip to content

Instantly share code, notes, and snippets.

@wolever
Created November 30, 2015 23:34
Show Gist options
  • Save wolever/7f52a3252f2d82ae437a to your computer and use it in GitHub Desktop.
Save wolever/7f52a3252f2d82ae437a to your computer and use it in GitHub Desktop.
bp: a small wrapper to make promises bindable in Angular
ngModule.factory('bp', function() {
return function(q) {
q.state = 'pending';
q.isPending = true;
q.isFulfilled = false;
q.isRejected = false;
q.then(function(result) {
q.state = 'fulfilled';
q.isPending = false;
q.isFulfilled = true;
q.isRejected = false;
q.result = result;
}, function(result) {
q.state = 'rejected';
q.isPending = false;
q.isFulfilled = false;
q.isRejected = true;
q.result = result;
});
return q;
}
});
ngModule.controller('ExampleCtrl', function(bp, $http) {
var req = $http.get("http://example.com/foo.json");
req = req.then(data => {
return loadData(data);
});
this.req = bp(req);
})
<div ng-controller="ExampleCtrl as e">
<span ng-if="e.req.isPending" class="loading-spinner"></span>
<div ng-switch="e.req.state">
<div ng-case-when="pending">Loading…</div>
<div ng-case-default>Error loading data: {{ e.req.result }}</div>
<div ng-case-when="fulfilled">
Your data: {{ e.req.result }}
</div>
</div>
</div>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment