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

Referencing deep properties safely using $parse


When dealing with object access, a seasoned JavaScript developer will be quite familiar with this error message:

TypeError: Cannot read property '...' of undefined

This, of course, is the result of attempting to access a property on an object that does not exist in the current lexical scope. It is often the case that the developer is aware of the possibility that the referenced object can be undefined, but it would be preferred that a failed property access returns undefined instead of throwing an error.

How to do it…

The typical use case is an asynchronous method that references a piece of data that isn't necessarily initialized before use.

Suppose that the user object in this example is populated with a user object served from the backend, filled upon login authentication, and cleared upon logging out, as shown here:

(app.js)

angular.module('myApp', [])
.controller('Ctrl', function($log, $scope) {
  $scope.$watch('user', function(newUserVal) ...