Angular Watchers
As I continue to work with Angularjs I continue to be impressed by all of the power the frame work offers a developer that can be leveraged to do some really neat things.
Recently though I had need to build out a dynamically generated list from an array of variable length with each needing a watcher on a boolean to check for a change to that boolean. This sounded simple enough to do to start. Simply utilize ng-repeat with that array and you are off to the races.
I had already created watchers with ease before so I figured it was just a matter of figuring out which $scope.$watch function to use. Was it a simple $watch, $watchCollection, or $watchgroup. Also should I watch the array as a whole or should I watch the objects, or the booleans themselves.
Suddenly what I had thought simple became more thought provoking. It became more infuriating then thoughtful though as I delved into implementation. It seemed that nothing I tried would actually watch for the change in those boolean flags. I tried all of the various options above but angular seemed unaware of the boolean as it changed value. It would note the initial setting of the values from the watcher, but nothing else after that.
So after spending a long time trying to make it do what I wanted I finally gave in and asked for help from a more experienced angular developer. He showed me a different way to watch an object then I was used to.
I had always used the format:
$scope.$watch(’array[0].boolean’, function(newVal, oldVal){...});
He showed me that when the “magic string” does not seem to grab the value that you are looking to watch you can tell angular specifically which value to watch by returning it in a function like so:
$scope.$watch(function() { return array[0].boolean}, function(newVal, oldVal){...});
This immediately solved my problem and all of my functionality began to work as soon as I switched to this new format for these booleans. This method can be less performant that the method of passing angular the variable in a string, but it is worth to note that this is an option when that will not work.






