Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

ng-click vs watch in Angular

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...

like image 469
cyberwombat Avatar asked Jan 30 '13 18:01

cyberwombat


People also ask

What is the difference between Ng-click and Onclick?

Another significant difference between ng-click and onclick is the execution context. Code inside an onclick attribute executes against the global window object, while an expression inside of ng-click executes against a specific scope object, typically the scope object representing the model for the current controller.

What is difference between Ng-click and data Ng-click in AngularJS?

They are the same thing. You can use data-ng-click to make a valid html.

What is the use of NG-click?

The ng-click directive tells AngularJS what to do when an HTML element is clicked.

Can we use NG-click and Onclick together?

For a single btn, it's ok to use ng-click or onclick in the ng-app . There is no difference between the two functions. For effective team work, you,d better to have an account with each other. In Angular apps, ng-click is recommended.


1 Answers

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.

like image 194
Sruti Avatar answered Oct 01 '22 00:10

Sruti