Skip to content

Comment on AngularJS 1.2.0: timely-deliveryparent

Comments

Can you give an example of where you've had to use $watch? Usually too many $watch is an indication that you could improve your app's architecture, e.g. by abstracting into directives.

FWIW I'm only speaking from personal experience and in your case lots of $watch might be necessary.

A good example is where I have a list of items which is filtered by a select[1]. I have the select wired up to the controller with a two-way binding and the controller watches for changes to the binding and filters the list accordingly. Maybe this isn't an idiomatic way to do it?

[1] http://plnkr.co/edit/ykfblPHlwkBJyMeObFyV?p=preview

Here's your example without a watch: http://plnkr.co/edit/GCv7bQALiOTgJ0npavwi?p=preview

That looks interesting, so does the filter reevaluate automatically when any of the variables used in the expression change?

edit: and thanks a lot for taking the time to look at it!

Ah, so I see that anything associated to the scope is reavaluated whenever anything else in the scope changes. Here's a further modification based on yours that keeps the criteria on the controller.

[1] http://plnkr.co/edit/JYyUvyh30e5L9KwVjDW2?p=preview

[2] http://plnkr.co/edit/ffYb14JjgSip5BTITILS?p=preview

edit: much happier with this version than the one I started with, thanks

edit: added example [2] which doesn't require a watch but still uses the service to do the filtering (because in my app it's actually an ajax call)

AboutSource Built by g1lg1l

Hackerly is an independent reader for Hacker News, built on the public HN API. Not affiliated with Y Combinator.