Am having a small query understanding a piece of code.
I was under the impression that $watchCollection will watch arrays, when passed as parameter according to this syntax:
$watchCollection(obj, listener);
My query however is in this piece of code:
var exp = $parse(attrs.chartData);
var salesDataToPlot=exp(scope);
which is then used in:
scope.$watchCollection(exp, function(newVal, oldVal){
salesDataToPlot=newVal;
redrawLineChart();
});
"exp" is of type function, and when i tried to pass it as an array, i got the “Cannot read property 'length' of undefined” error. I got that error when i tried this Code :
var salesData = scope[iAttrs.chartData];
.
.
.
.
scope.$watchCollection(salesData, function(newVal, oldVal){
salesDataToPlot=newVal;
redrawLineChart();
});
Why coudn't i pass salesData as an array to $watchCollection?
Here's my pen
$parse service takes an expression, and turns it into a function, that will resolve to actual data when given a context, which is usually the scope.
var exp = $parse(attrs.chartData); // exp is an expression function that needs context
var salesDataToPlot=exp(scope); is the actual result of supplying exp with context - the scope. The result is the array you need
Just watch salesDataToPlot (pen):
scope.salesDataToPlot = salesDataToPlot;
scope.$watchCollection('salesDataToPlot', function(newVal, oldVal){
salesDataToPlot=newVal;
redrawLineChart();
});
Using salesData directly throws an error because salesData is a property on scope, and not a variable available in this closure. To make $watchCollection look for this property on the scope, you'll have to use "salesData" (pen).
scope.$watchCollection("salesData", function(newVal, oldVal){
salesDataToPlot=newVal;
redrawLineChart();
});
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With