【发布时间】:2017-05-31 19:37:27
【问题描述】:
我在一个 Angular 应用程序中工作,并且在一个控制器内部我需要迭代一个对象数组。这是这种情况下涉及的控制器和代码:
myapp.controller('LoginController', ['$scope', function(scope) {
// Users for test
this.users = [
{
name: 'admin',
password: 'admin',
role: 'ADMIN'
},
{
name: 'employee',
password: '12345',
role: 'EMPLOYEE'
}
];
console.dir(this.users); // Prints an array of objects correctly
// called when user submits
scope.login = function() {
console.log('login(). User: ');
console.dir(scope.user); // Prints the object with user's input (also correct)
var found = false;
for(let u of this.users) {
console.log('Comparing with:');
console.dir(u);
if(u.name == scope.user.name && u.password == scope.user.password) {
console.log('Found!');
found = true;
// do something else...
}
}
if(!found) { // show error message... }
}
}]);
问题是当我提交登录表单(调用scope.login())时,我在控制台中收到一条错误消息:
TypeError: Cannot read property 'Symbol(Symbol.iterator)' of undefined
at m.scope.login (loginController.js:44)
...
loginController.js:44 对应于for(let u of this.users) { 行。我在网上搜索(W3 Schools、MDN 和这个网站),但解决方案对我不起作用。我已经尝试了以下解决方案:
for(var u of this.users)var u; for(u in this.users)-
for(var i = 0; i < this.users.lenght; i++):这会将错误消息更改为Cannot read property 'length' of undefined
我觉得这很简单,但我不知道它是什么(我对 Javascript 不是很熟练,抱歉)。谁能帮我解决这个问题?
提前感谢您的回答。
【问题讨论】:
-
this.users未定义吗? -
你为什么使用
this?您应该不使用scope还是只使用普通的var或let?因为当你到达函数时,this指的是函数 -
@Chifilly 这是
controller as语法。首选$scope
标签: javascript angularjs loops