Chapter 8: Using promises with Restangular
by msfrisbie
HTML
<script src="https://code.angularjs.org/1.3.2/angular.min.js"></script>
<script src="//cdnjs.cloudflare.com/ajax/libs/restangular/1.4.0/restangular.min.js"></script>
<script src="//cdnjs.cloudflare.com/ajax/libs/underscore.js/1.7.0/underscore-min.js"></script>
<div ng-app="myApp">
<div ng-controller="Ctrl">
<button ng-click="getOneWidget()">Get One Widget</button>
<button ng-click="getManyWidgets()">Get Many Widgets</button>
{{ status }}
<div />
</div>
JavaScript
angular.module('myApp', ['restangular'])
.controller('Ctrl', function($scope, Restangular) {
$scope.getOneWidget = function() {
Restangular
.one('widget', 4)
// get() will return a promise for the GET request
.get()
.then(
function(data) {
// consume response data in success handler
$scope.status = 'One widget success!';
},
function(response) {
// consume response message in error handler
$scope.status = 'One widget failure!';
}
);
};
// generally, the API mapping is stored in a variable,
// and the promise-returning method will be invoked as needed
var widgets = Restangular.all('widgets');
$scope.getManyWidgets = function() {
// create the request promise
widgets.getList()
.then(function(widgets) {
// success handler
$scope.status = 'Many widgets success!';
}, function() {
// error handler
$scope.status = 'Many widgets failure!';
});
};
});