Andrew Kim Andrew Kim - 3 months ago 14
AngularJS Question

Why does angular allow dynamic object creation?

I'm not sure if the title is correctly conveying the feature i'd like clarity on. But let me lay it out.

In javascript we can instantiate a variable to an empty object:

var person = {};


We can easily set properties to it

person.name = "Bob"


We can't, however, assign objects by using properties:

person.pet.name = "Bob"
> Uncaught TypeError: Cannot set property 'name' of undefined


In angular you can. This modest code for example. I have a controller:

angular.module('someModule', [])
.controller('someController', [
Callback
]

function Callback(){
this.person = {}
}


Then the view contains:

<input type="text" data-ng-model='vm.person.pet.name'>


Where
vm
is the viewmodel representing the controller. When I log the results grabbed from the input you get a
person
object with a
pet
child object with a property of
name


What gives? Why did angular add this feature?(i assume feature) Is it strictly for flexibility?

Answer

From the docs:

Forgiving

Expression evaluation is forgiving to undefined and null. In JavaScript, evaluating a.b.c throws an exception if a is not an object. While this makes sense for a general purpose language, the expression evaluations are primarily used for data binding, which often look like this:

{{a.b.c}}

It makes more sense to show nothing than to throw an exception if a is undefined (perhaps we are waiting for the server response, and it will become defined soon). If expression evaluation wasn't forgiving we'd have to write bindings that clutter the code, for example: {{((a||{}).b||{}).c}}

Similarly, invoking a function a.b.c() on undefined or null simply returns undefined.

In short, expression in html <input type="text" data-ng-model='vm.person.pet.name'> doesn't change in time, however an actual value of vm.person.pet.name does.