正在通过一个小查询理解一段代码。

我的印象是,当根据以下语法作为参数传递$ watchCollection时,它将监视数组:


$ watchCollection(obj,监听器);


但是我的查询在这段代码中:

  var exp = $parse(attrs.chartData);
  var salesDataToPlot=exp(scope);


然后用于:

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


“ exp”是类型函数,当我尝试将其作为数组传递时,出现“无法读取属性'length'of undefined”错误。
我尝试此代码时遇到了该错误:

  var salesData = scope[iAttrs.chartData];

.
.
.
.

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


为什么我不能将salesData作为数组传递给$ watchCollection?

Here's my pen

最佳答案

$parse服务接受一个表达式,并将其转换为一个函数,当给定上下文(通常是作用域)时,它将解析为实际数据。

  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


只要看salesDataToPlot(pen):

scope.salesDataToPlot = salesDataToPlot;

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


直接使用salesData会引发错误,因为salesData是作用域的属性,而不是此闭包中可用的变量。要使$ watchCollection在范围内寻找此属性,您必须使用“ salesData”(pen)。

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

07-25 22:01