$ WatchCollection parameters required return an error when passed as an array

Has a small request that understands a piece of code.

I was under the impression that $ watchCollection would watch arrays passed as parameters according to this syntax:

$ watchCollection (obj, listener);

My request, 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" has a type function, and when I tried to pass it as an array, I got the error "Can not read property" from undefined. I got this 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 is my feather

+5
source share
1 answer

The $ parse service takes an expression and turns it into a function that will resolve the actual data while providing a context, which is usually a 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 look at salesDataToPlot ( pen ):

 scope.salesDataToPlot = salesDataToPlot; scope.$watchCollection('salesDataToPlot', function(newVal, oldVal){ salesDataToPlot=newVal; redrawLineChart(); }); 

Using salesData directly causes an error, because salesData is a property in scope, not a variable, available in this closure. To make $ watchCollection look for this property in scope, you will have to use "salesData" ( pen ).

  scope.$watchCollection("salesData", function(newVal, oldVal){ salesDataToPlot=newVal; redrawLineChart(); }); 
+2
source

All Articles