Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

$watchCollection parameters required returns error, when passed as an array

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

like image 666
Nevin Madhukar K Avatar asked Oct 30 '22 21:10

Nevin Madhukar K


1 Answers

$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();
               });
like image 123
Ori Drori Avatar answered Nov 15 '22 06:11

Ori Drori