I'm trying to distinguish between internal change and an external change with a two-way data-bound attribute ('='
).
In other words: I don't want to $watch
to fire on the value if the change was internal (i.e. the scope variable was changed in the controller or in the link function).
Here some code that illustrates my problem:
HTML
<div ng-app="myApp"> <div ng-controller="MainCtrl"> <input ng-model="value"/> <mydemo value="value"></mydemo> </div> </div>
Javascript
app.directive('mydemo', function () { return { restrict: 'E', scope: { value: "=" }, template: "<div id='mydiv'>Click to change value attribute</div> Value:{{value}}", link: function (scope, elm) { scope.$watch('value', function (newVal) { //Don't listen if the change came from changeValue function //Listen if the change came from input element }); // Otherwise keep any model syncing here. var changeValue = function() { scope.$apply(function () { scope.value = " from changeValue function"; }); } elm.bind('click', changeValue); } } })
Live demo: http://jsfiddle.net/B7hT5/11/
Any idea who can I distinguish?