Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Angular JS $watch vs $on

I want to execute a function inside a directive, whenever there is a state change in the parent scope.

The obvious way to achieve this is to use event broadcasts ($broadcast) and listeners ($on).

I am curious if using a $watch is an alternative to event broadcast. If it is, how do the two compare?

As far as I understand, the expression to be watched is evaluated every $digest cycle. So are events more efficient than watch?

like image 414
Yogesh Mangaj Avatar asked May 09 '14 09:05

Yogesh Mangaj


People also ask

What is $Watch in AngularJS?

$watch() function is used to watch the changes of variables in $scope object. Generally the $watch() function will create internally in Angularjs to handle variable changes in application.

Which is best node js or AngularJS?

Node. js is more preferable when faster and scalable web development is needed. It is usually used for building small-sized projects. Angular is preferred when real-time applications, for example, chat apps, or instant messaging are needed.

What is difference between Nodejs and AngularJS?

AngularJS is a client-side framework. Node. js is a cross-platform runtime environment. AngularJS supports two-way data binding but cannot support database query writing features.

Can I use node js with AngularJS?

If you are writing an AngularJS front end web application, you may never have to use NodeJS. If you need tooling (build scripts to compile Sass, linters, etc) in your development or deployment process you can use NodeJS task runners like Gulp, Grunt or Webpack.


1 Answers

The $watch function is used to watch variables on the scope. Scope inheritance allows you to watch parent scope variables as well, so that is definitely the way to go for your use case. As you correctly said, $on is used to watch for events, which you can $broadcast to child scopes or $emit to parent scopes. This gives you much more control, but it might cause more mistakes while coding, since you could get an update to a scope variable from a point which you don't monitor and forget to notify the listeners.

You can still use events when you don't inherit scope variables. But be careful not to pollute a large scope, using services might be an option there, because you immediately see whether it is injected or not.

Since a directive gets the scope it is on (or inherits from it), I would say $watch is a much cleaner option here.

If you want to have an isolated scope on your directive, you can pass arguments as attributes and $observe them.

like image 56
Ferdinand Torggler Avatar answered Oct 23 '22 19:10

Ferdinand Torggler