我正在开发一个有角度的应用程序,我有一个表单,它几乎没有规则存储在名为ruleList的列表中,然后存储到后端。为了在页面中显示这些规则,我正在准备ruleList再次迭代存储在后端的ruleList。
ruleList有一个字段'groupByField',它也是一个列表。当我遍历准备每个规则的ruleList时,有一个异步操作来准备groupByField列表。在准备groupByField列表时,ruleObj被推送到$ scope.ruleList,而不包括groupByField。因此破坏了我的代码。如何确保将groupByfield列表推送到ruleList中的相应ruleObj。
$scope.ruleList = [];
_.each(alertcfg.ruleList, function(rule, index) {
var ruleObj = { 'selectedIndex':'',
'groupByField':[],
'indexFields':[]
}
if ( rule.selectedIndex != '' ) {
//async calls
courier.indexPatterns.get(rule.selectedIndex).then(function(current_index) {
var fields = current_index.fields
rule.indexFields = fields
_.each(rule.indexFields, function(field) {
_.each(rule.groupByField, function(grp_by_field) {
if(grp_by_field.name === field.name)
{
ruleObj.groupByField.push(grp_by_field);
}
});
});
})
}
$scope.ruleList.push(ruleObj);
$scope.operRuleList.push(operRuleObj);
});
答案 0 :(得分:0)
你的ruleObj插入在promise之外然后阻塞,将其移到里面:
//async calls
courier.indexPatterns.get(rule.selectedIndex).then(function (current_index) {
var fields = current_index.fields;
rule.indexFields = fields;
_.each(rule.indexFields, function(field) {
_.each(rule.groupByField, function(grp_by_field) {
if (grp_by_field.name === field.name) {
ruleObj.groupByField.push(grp_by_field);
}
});
});
$scope.ruleList.push(ruleObj);
});
如果你需要在ajax失败的情况下推送默认的空ruleObj,请使用第二个param然后阻止:
//async calls
courier.indexPatterns.get(rule.selectedIndex).then(function (current_index) {
var fields = current_index.fields;
rule.indexFields = fields;
_.each(rule.indexFields, function(field) {
_.each(rule.groupByField, function(grp_by_field) {
if (grp_by_field.name === field.name) {
ruleObj.groupByField.push(grp_by_field);
}
});
});
$scope.ruleList.push(ruleObj);
}, function (err) {
// ajax failure case
$scope.ruleList.push(ruleObj);
});