【发布时间】:2014-09-29 10:38:19
【问题描述】:
AngularJS 1.2.21 中是否存在与 forEach 相关但 AngularJS 1.2.20 中没有的错误?
我测试了以下代码(加载 ng-grid 时):
var contor = 0;
$scope.$watch('gridOptions.$gridScope.columns', functionForColumnsChange, true);
...
function functionForColumnsChange(newv, oldv) {
if ( newv !== oldv ) {
console.log(contor++);
}
}
如果我使用:
https://ajax.googleapis.com/ajax/libs/angularjs/1.2.20/angular.js
输出是
0
但如果我使用
https://ajax.googleapis.com/ajax/libs/angularjs/1.2.21/angular.js
输出是
TypeError:无法设置未定义的属性“sortPriority” 在http://angular-ui.github.io/ng-grid/lib/ng-grid.js:1668:36 在 Object.forEach (https://ajax.googleapis.com/ajax/libs/angularjs/1.2.21/angular.js:325:18) 在 self.sortData (http://angular-ui.github.io/ng-grid/lib/ng-grid.js:1667:25) 在 self.sortColumnsInit (http://angular-ui.github.io/ng-grid/lib/ng-grid.js:1701:18) 在 Object.ngGridDirectives.directive.ngGridDirective.compile.pre.grid.init.then.dataWatcher [as fn] (http://angular-ui.github.io/ng-grid/lib/ng-grid.js:2943:42) 在 Scope.$get.Scope.$digest (https://ajax.googleapis.com/ajax/libs/angularjs/1.2.21/angular.js:12471:29) 在 Scope.$get.Scope.$apply (https://ajax.googleapis.com/ajax/libs/angularjs/1.2.21/angular.js:12736:24) 在https://ajax.googleapis.com/ajax/libs/angularjs/1.2.21/angular.js:1438:15 在 Object.invoke (https://ajax.googleapis.com/ajax/libs/angularjs/1.2.21/angular.js:3940:17) 在 doBootstrap (https://ajax.googleapis.com/ajax/libs/angularjs/1.2.21/angular.js:1436:14)
0
1
为什么会出现这个错误? 为什么 0 之后是 1?
如果我更改 ng-grid.js 注释 2 行:
//c.sortPriority = i + 1;
//push(c);
错误信息不存在了,但是有“1”。
使用的 ng-grid 来自这个来源:http://angular-ui.github.io/ng-grid/lib/ng-grid.js(缩小版也有同样的问题)。
后期编辑: 问题似乎和这个问题有关:https://github.com/angular/angular.js/commit/36625de0d3ebc1fc091af474d942c6ce16b0a1c0
区别仅在于 Google Chrome 和 Mozilla Firefox。
在 IE8 中,AngularJS 的两个版本都打印了 0 和 1。 IE8 中的输出:
TypeError: 'undefined' 为 null 或不是对象
0
1
【问题讨论】:
-
$watch.. 的错误是什么?您使用的ng-grid库在不同的角度版本上导致错误,您希望$watch的行为如何?您知道库中出了什么问题以及它对错误的作用吗? -
附上你的代码,做一个JSFiddle,你现在所拥有的不足以重现这个问题。
ng-grid正在迭代一个列数组,其中一个是未定义的。尝试制作一个 JSFiddle 来重现两个版本的问题。 -
您可以做的是替换全局角度对象上的 forEach 函数,并使用您在 Github 上链接的旧功能。
-
我找到了解决这个问题的方法。我在本地机器上获取了 AngularJS 代码,并在行前添加了一个条件,因为数组似乎很稀疏。因此,我更改了 forEach 源代码,在 for 循环中添加: if ( typeof obj[key] !== 'undefined' )。
-
更好的解决方案是只修改 ng-grid 以使用新的 AngularJS: if (isArr) { angular.forEach(col, function (c, i) { if ( typeof c !== '未定义' ) { c.sortPriority = i + 1; push(c); } });
标签: javascript angularjs foreach ng-grid watch