Enter Your Email Address to Watch This Lesson

Your link to unlock this lesson will be sent to this email address.

Unlock this lesson and all 959 of the free egghead.io lessons, plus get Angular 1.x content delivered directly to your inbox!



Existing egghead members will not see this. Sign in.

New in Angular 1.3 - $scope.$watchGroup

2:42 Angular 1.x lesson by

With Angular 1.3 you now have access to $scope.$watchGroup. This allows you to monitor an array of expressions for change. This is useful when you want to perform the some logic when any item in a group changes.

Get the Code Now
click to level up

egghead.io comment guidelines

Avatar
egghead.io

With Angular 1.3 you now have access to $scope.$watchGroup. This allows you to monitor an array of expressions for change. This is useful when you want to perform the some logic when any item in a group changes.

Man 1: This is another video about the cool things coming in Angular 1.3. As you can see, I'm using release candidate .3 here. We're going to be talking about scope.watchGroup. WatchGroup is coming in 1.3. It's actually very simple.

You just say, "Scope.watchGroup." You hand it an array and a listener. Then that array of things will be watched.

We have a very simple demo app here. Labels and inputs bound to the vals, as you can see here.

We want to watch the value of all of these and respond in the same way for every one of these. And so, this is a good use case for watchGroup.

All that you need to do is give an array of expressions. We can say val 1, val 2, val 3, val 4. This is because all of those are on the scope.

If we had something else that we wanted to watch, as well, then we'd say function and return some value. That would also be a legitimate, valid expression.

But just for simplicity here, it's basically anything that you would pass in a normal scope.watch. Anything that you'd pass in as the first argument here, right here, would be considered a valid expression that you could put as an item in this array.

Let's see what we get as our arguments to our listener function. Let's say newVal, oldVal. We'll assign this to the scope so scope.newVal = newVal. Scope.oldVal = oldVal. Then we'll just add those here.

We'll say h3newVal and pre newVal. Pipe that through json. We'll do the same for oldVal.

Now, as I change things, watch what happens. NewVal now has val for the first item. OldVal still has val 1. That's expected. You can see, as I change things that's how it's being updated.

You see the order of items in this array, in the newVal array, being assigned to this newVal is the same order as this watch group.

And so, I could say, "Scope.newVal1 = newVal" and the first item in the array, for example.

That's what watchGroup does. It is pretty simple. Hopefully you can find a good use for it.

HEY, QUICK QUESTION!
Joel's Head
Why are we asking?