我有一个像这样的json:
{
"0":{"login":"user1","licenses":{"x":4},"open":true},
"1":{"login":"user2","licenses":{"x":6,"xx":9,"xxx":7},"open":true}
}
和这个
<select ng-model="userToAdd" ng-options="user.login as user.login for user in listUsers"></select>
不起作用,但我不知道为什么。
以下是相关的控制器代码:
$scope.getUsers = function() {
$scope.listUsers = {};
var indexLogin = 0;
var indexLicense = 0;
$http.get('listUser').success(function(data) {
_.each(data, function(licenses, userLogin){
$scope.listUsers[indexLogin] = {};
$scope.listUsers[indexLogin].login = userLogin;
$scope.listUsers[indexLogin].licenses = {};
_.each(licenses, function(license){
if(license.feature.name in $scope.listUsers[indexLogin].licenses){
$scope.listUsers[indexLogin].licenses[license.feature.name] = $scope.listUsers[indexLogin].licenses[license.feature.name] + 1;
} else {
$scope.listUsers[indexLogin].licenses[license.feature.name] = 1;
}
indexLicense++;
})
$scope.listUsers[indexLogin].open = false;
indexLogin++;
})
});
};
最佳答案
您的listUsers
是一个对象,而不是数组。因此,应该相应地更改ng-options:
ng-options="user.login as user.login for (_, user) in listUsers"
另外,您可能想更改
listUsers
格式,使其成为适当的数组。无需使用递增的indexLogin
,只需在每个步骤创建一个新对象,然后将该对象推入listUsers
数组,并使用_.map
准备适当的对象数组:$scope.listUsers = [];
$http.get('listUser').success(function(data) {
$scope.listUsers = _.map(data, function(licenses, userLogin){
var user = {
login: userLogin,
open: false,
licences: {}
};
_.each(licenses, function(license){
var featureName = license.feature.name;
user.licences[featureName] = (user.licences[featureName] || 0) + 1;
});
return user;
})
});