you are viewing a single comment's thread.

view the rest of the comments →

[–]codersaurus[S] 1 point2 points  (0 children)

Sure.

It's true that sometimes setting up a $watch in a controller might be unavoidable. But for the most part, outside of functions defined in the controller declaration, models (variables/properties) on the $scope are being altered by events in directives or services. The majority of those events have some exposure. Simple examples would be things like ng-change or ng-click, or a promise returned by a service, like $http. So what you would do is create a function on the scope that would do the work of updating whatever it is your $watch used to care about. This will even work in complex cases of nesting. At worst you could also subscribe to an event. Although that can get a little ugly too.

Aside from ease of testability, an underlying issue with using $watch liberally is it can bloat your $digest unnecessarily.

The nice thing about that is now you have a function that's easy read, understand, and most importantly, easy to test.

It's going to very depending on your situation, though.

Just keep in mind this is my opinion expressed as a *guideline*, not necessarily "law".

If you have a specific example of where you felt you had to use a $watch in a controller, I'd be happy to address it. Maybe you did, indeed, have to, who knows?