1+ <!doctype html>
2+ < html ng-app ="Demo ">
3+ < head >
4+ < meta charset ="utf-8 " />
5+
6+ < title >
7+ Watching Object Literal Expressions In AngularJS
8+ </ title >
9+ </ head >
10+ < body ng-controller ="AppController ">
11+
12+ < h1 >
13+ Watching Object Literal Expressions In AngularJS
14+ </ h1 >
15+
16+
17+ <!-- Load scripts. -->
18+ < script type ="text/javascript " src ="../../vendor/jquery/jquery-2.1.0.min.js "> </ script >
19+ < script type ="text/javascript " src ="../../vendor/angularjs/angular-1.2.4.min.js "> </ script >
20+ < script type ="text/javascript ">
21+
22+ // Create an application module for our demo.
23+ var app = angular . module ( "Demo" , [ ] ) ;
24+
25+
26+ // -------------------------------------------------- //
27+ // -------------------------------------------------- //
28+
29+
30+ // I control the root of the application.
31+ app . controller (
32+ "AppController" ,
33+ function ( $scope , $parse ) {
34+
35+ $scope . friend = {
36+ id : 4 ,
37+ name : "Heather"
38+ } ;
39+
40+
41+ // When we parse an AngularJS expression, we get back a function that
42+ // will evaluate the given expression in the context of a given $scope.
43+ var getter = $parse ( "{ name: friend.name }" ) ;
44+
45+ // Get the result twice.
46+ var a = getter ( $scope ) ;
47+ var b = getter ( $scope ) ;
48+
49+ // Check to see if evaluating the AngularJS expression above returns a
50+ // new object each time.
51+ // --
52+ // HINT: It does (return a new object each time).
53+ console . log ( "Objects are equal:" , ( a === b ) ) ;
54+
55+
56+ // Since a new object is returned each time the Object Expression is
57+ // evaluated by AngularJS, we havd to use DEEP object equality.
58+ // Otherwise, the object reference will be different on EACH $digest
59+ // iteration, which will cause the digest to run forever (or rather,
60+ // to error out).
61+ $scope . $watch (
62+ "{ name: friend.name }" ,
63+ function ( newValue , oldValue ) {
64+
65+ console . log ( "Watch:" , newValue . name ) ;
66+
67+ } ,
68+
69+ // Deep object equality.
70+ true
71+ ) ;
72+
73+ }
74+ ) ;
75+
76+ </ script >
77+
78+ </ body >
79+ </ html >
0 commit comments