Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

AngularJS $watch for value changes after initialization

I have this situation where I need to capture the event when a model is changed but the initialization in my directive triggers the event too early.

Plunker: http://plnkr.co/edit/2T0Rq6yOXHWxQAOv8RpX?p=preview

How can I overcome this? Setting some flags, but how/where? Other approaches?

Thanks!

UPDATE

I added the value attribute to the directive so you can understand better what I mean by initialization.

Plunker: http://plnkr.co/edit/a5fzJi7VzAytj3Urj06L?p=preview

like image 948
Andrei Canta Avatar asked Oct 02 '22 17:10

Andrei Canta


2 Answers

I solved it finally!

Plunker: http://plnkr.co/edit/a5fzJi7VzAytj3Urj06L?p=preview

The form directive in Angular has a property called $dirty. It starts as false and when you change the value of an input, the ngModel directive makes the form "dirty". First I tried to use ngModel in my directives but I ended up requiring using the form directly.

PS. This is triggered only on the first change, but this is exactly what I needed.

like image 198
Andrei Canta Avatar answered Oct 12 '22 10:10

Andrei Canta


You define data as

$scope.data = { x: 51 }

Later during parsing Angular detects that there are two more properties: y and z and they are undefined. In directive you set them to 0 in this case. So your data object becomes

{ x: 51, y: 0, z: 0 }

Obviously that $scope.data has changed and watcher should fire. This is why it happens.

To solve this you can simply define data with initial y and z values:

$scope.data = { x: 51, y: 0, z: 0 };

Demo: http://plnkr.co/edit/RfztKvrxhzPYMoSss7Fm?p=preview

like image 41
dfsq Avatar answered Oct 12 '22 10:10

dfsq