angularjs – $watchCollection参数在作为数组传递时返回错误
发布时间:2020-12-17 07:14:01 所属栏目:安全 来源:网络整理
导读:我有一个小查询了解一段代码. 我认为$watchCollection将根据以下语法作为参数传递时监视数组: $watchCollection(obj,listener); 我的查询是在这段代码中: var exp = $parse(attrs.chartData); var salesDataToPlot=exp(scope); 然后用于: scope.$watchCol
我有一个小查询了解一段代码.
我认为$watchCollection将根据以下语法作为参数传递时监视数组:
我的查询是在这段代码中: var exp = $parse(attrs.chartData); var salesDataToPlot=exp(scope); 然后用于: scope.$watchCollection(exp,function(newVal,oldVal){ salesDataToPlot=newVal; redrawLineChart(); }); “exp”是类型函数,当我试图将它作为数组传递时,我得到了“无法读取未定义的属性’长度”错误. var salesData = scope[iAttrs.chartData]; . . . . scope.$watchCollection(salesData,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',oldVal){ salesDataToPlot=newVal; redrawLineChart(); }); 使用salesData会直接抛出错误,因为salesData是作用域的属性,而不是此闭包中可用的变量.要使$watchCollection在作用域上查找此属性,您必须使用“salesData”(pen). scope.$watchCollection("salesData",oldVal){ salesDataToPlot=newVal; redrawLineChart(); }); (编辑:李大同) 【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容! |