Mastering Web Application

(Rick Simeone) #1
Chapter 1

There are several ways of influencing properties defined on a parent scope from a
child scope. Firstly, we could explicitly reference a parent scope using the $parent
property. A modified template would look as follows:


<input type="text" ng-model="$parent.name">

While it is possible to solve an issue using this example by directly referencing a
parent scope, we need to realize that this is a very fragile solution. The trouble is
that an expression used by the ng-model directive makes strong assumptions about
the overall DOM structure. It is enough to insert another scope-creating directive
somewhere above the tag and $parent will be pointing to a completely
different scope.


As a rule of thumb, try to avoid using the $parent property as it
strongly links AngularJS expressions to the DOM structure created
by your templates. An application might easily break as a result of
simple changes in its HTML structure.

Another solution involves binding to a property of an object and not directly to a
scope's property. The code for this solution is as follows:


<body ng-app ng-init="thing = {name : 'World'}">
<h1>Hello, {{thing.name}}</h1>
<div ng-controller="HelloCtrl">
Say hello to: <input type="text" ng-model="thing.name">
<h2>Hello, {{thing.name}}!</h2>
</div>
</body>

This approach is much better as it doesn't assume anything about the DOM
tree structure.


Avoid direct bindings to scope's properties. Two-way data binding to
object's properties (exposed on a scope) is a preferred approach.
As a rule of thumb, you should have a dot in an expression provided
to the ng-model directive (for example, ng-model="thing.name").
Free download pdf