I have a directive which loads a JSON file then uses that data to create an HTML5 canvas drawing (i.e the json data holds things such as text, color, position). I also have a number of input fields (text, sliders, etc) that allow the user to manipulate the drawing. I see that I can either $watch each of these element or use ng-click and call a function – is there a recommended approach?
Some perhaps relevant notes:
- The form element and the canvas are all part of the same directive template
- The form elements react onchange so no submit button
- Each of these form element value get checked, maybe converted then they modify the json string. I then call a refresh function which reloads my canvas with the new data.
It’s possible that I am approaching this the wrong way too…
So, from what I understand there are some actions by user on some elements (within a directive) and you have to do something every time these events are fired.
The intent of $watch is to ‘watch’ / do something every time a particular variable’s value changes.
$scope.$watch('watchedVariable', onWatchedVariableChangedFn)where onWatchedVariableChangedFn is a function. This is triggered only when the value actually changes, irrespective of what causes the change.On the other hand, you can hook up event handlers to the markup attributes, like
ng-click='onClickFn()'. These get fired from actions on the UI elements. [Also note ng-click will work only on clickable elements. You seem to have multiple elements (text, sliders, etc).]You might have to see what exactly can cause the change of these values / cause you to redraw your canvas and then decide which way you want to go.
Edit : A third alternate you might want to consider is to fire events ($emit / $broadcast) and handle ($on) those events wherever applicable.