【发布时间】:2016-01-07 22:44:25
【问题描述】:
这段代码的奇怪行为:
我有一些 Angular 控制器:
.controller('View1Ctrl', ['$scope', 'CrawlServerExecutor', function ($scope, CrawlServerExecutor) {
$scope.results = [];
var showResults = function (results) {
results.forEach(function (result) {
$scope.results.push(result);
});
};
这样写的时候:
var showResults = function (results) {
results.forEach($scope.results.push);
};
我收到此错误:
Error: undefined is not an object 试图访问 push 函数,我在调试器中查看了 $scope.results 并且该对象被识别为一个数组,但由于某种原因,在此语法中它没有引用它的 push 函数。我更喜欢这段代码,因为它更优雅。
有人知道为什么会这样吗?
谢谢
【问题讨论】:
-
您是否尝试过将数组绑定到函数(所以当它被调用时,
this将被正确设置),如results.forEach($scope.results.push.bind($scope.results)); -
@AlexCorreiaSantos - 你当然是对的。为什么不发布答案?
-
我没有机会测试,只是想从头顶上弄清楚,所以我不想给出错误的答案。很高兴它起作用(我已将其添加为答案)
-
showResults是否被重复调用?结果是汇总还是替换?并且参数 (results) 是类数组对象的数组吗? -
那为什么不简单地将值分配给属性,例如:
$scope.results = results;?
标签: javascript angularjs callback