$observe vs $watch

####Objective####

  1. Example of showing the difference between observe and watch
  2. Example of showing $eval

<!-- more --> <iframe style="margin: 20px 0; width: 100%; height: 250px" src="http://embed.plnkr.co/jxGl8aLKy1snCMlRbRxC" frameborder="0" allowfullscreen="allowfullscreen"></iframe>

MarkupGithub
1
2
3
4
<input type="text" ng-model="xinput" />
<div my-dir textinput='xinput' valinput=''></div>

AngularJSGithub
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
var app = angular.module('ngApp', [])
.directive('myDir', function () {
"use strict";
return {
scope: true,
template: '<div>observe-textinput: </div><div>observe-valinput: </div><div>eval: </div><div>eval2: </div><div>watch: </div>',
link: function (scope, iElement, iAttrs) {
iAttrs.$observe('textinput', function (value) {
scope.observe1 = value;
});
iAttrs.$observe('valinput', function (value) {
scope.observe2 = value;
});
scope.$watch(iAttrs.textinput, function (newVal, oldVal, scope) {
scope.evalVal = scope.$eval(iAttrs.textinput);
scope.evalVal2 = scope.$eval('xinput');
scope.watchVal = newVal;
}, false);
}
};
});
app.controller('MainCtrl', ['$scope', function ($scope) {
'use strict';
$scope.xinput = 'test';
}]);