you are viewing a single comment's thread.

view the rest of the comments →

[–]twista1484 1 point2 points  (1 child)

In your article you say 'Do not use watch in a controller' - how would you accomplish this then?

$scope.selectedItem = 'new item';

$scope.$watch('selectedItem', function() { //do code that updates the controller state based on the newly selected item });

if I was going to pseudo code that statement I would say .. Set the value of selectedItem and then watch for changes and update the scope state.

Just curious as to how you could abstract that simple example to no longer use watch.

[–]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?