Andrew Kim Andrew Kim - 1 year ago 101
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 = "Bob"

We can't, however, assign objects by using properties: = "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', [

function Callback(){
this.person = {}

Then the view contains:

<input type="text" data-ng-model=''>

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

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

Answer Source

From the docs:


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:


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=''> doesn't change in time, however an actual value of does.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download