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) { ...