Book Image

AngularJS Web application development Cookbook

By : Matthew Frisbie
Book Image

AngularJS Web application development Cookbook

By: Matthew Frisbie

Overview of this book

Packed with easy-to-follow recipes, this practical guide will show you how to unleash the full might of the AngularJS framework. Skip straight to practical solutions and quick, functional answers to your problems without hand-holding or slogging through the basics. Avoid antipatterns and pitfalls, and squeeze the maximum amount out of the most powerful parts of the framework, from creating promise-driven applications to building an extensible event bus. Throughout, take advantage of a clear problem-solving approach that offers code samples and explanations of components you should be using in your production applications.
Table of Contents (17 chapters)
AngularJS Web Application Development Cookbook
Credits
About the Author
About the Reviewers
www.PacktPub.com
Preface
Index

Using promises with Restangular


Restangular, the extremely popular REST API extension to AngularJS, takes a much more promise-centric approach compared to $resource.

How to do it…

The Restangular REST API mapping will always return a promise. This is shown here:

(app.js)

angular.module('myApp', ['restangular'])
.controller('Ctrl', function($scope, Restangular) {
  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');
  
  // create the request promise
  widgets.getList()
  .then(function(widgets) {
    // success handler
    ...