Created
November 30, 2015 23:34
-
-
Save wolever/7f52a3252f2d82ae437a to your computer and use it in GitHub Desktop.
bp: a small wrapper to make promises bindable in Angular
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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); | |
}) |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<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