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

Creating promise wrappers with $q.when()


AngularJS includes the $q.when() method that allows you to normalize JavaScript objects into promise objects.

How to do it…

The $q.when() method accepts promise and non-promise objects, as follows:

var deferred = $q.defer()
  , promise = deferred.promise;

$q.when(123);
$q.when(promise);
// both create new promise objects

If $q.when() is passed a non-promise object, it is effectively the same as creating an immediately resolved promise object, as shown here:

var newPromise = $q.when(123);

// promise will wait for a $digest cycle to update $$state.status,
// this forces it to update for inspection
$scope.$apply();

// inspecting the status reveals it has already resolved
$log.log(newPromise.$$state.status);
// 1

// since it is resolved, the handler will execute immediately
newPromise.then($log.log);
// 123

How it works…

The $q.when() method wraps whatever is passed to it with a new promise. If it is passed...