我正在使用角度ui网格库并尝试填充自定义下拉过滤器。这个过滤器只能应用于特定的列,这就是为什么我写了循环以便动态访问列的原因。对于每个特定的列,我通过我的角度服务向api发送一个请求,以获取过滤器的值,并且如果响应成功,我将每个列属性ID与返回的数据ID进行比较,然后填充过滤器值。可变变量可从角度服务中的闭包访问
这个问题似乎then
功能里面,IDE显示我警告
可变变量是从封闭
访问和内部的then
功能没有什么作品。
我在这里阅读了多个主题,发现我必须执行自调用功能,但它不起作用。
那么我的错误在哪里?在此先感谢
代码
for (var i = 0; i < $scope.columns.length; i++) {
// ===== rebuild columns tree =====
var execute_ids = [];
angular.forEach($scope.columns[i].property, function(){
if ($scope.columns[i].property.strict === true){
if(execute_ids.indexOf($scope.columns[i].property.propertyTypeId) === -1){
execute_ids.push($scope.columns[i].property.propertyTypeId);
lovServices.customPropFilterValue(execute_ids)
.then(function (response) {
(function() {
if (response.id == $scope.columns[i].property.propertyTypeId){
$scope.filter.push({
value: data.value,
label: data.value
});
$scope.columns[i].filter = {
type: uiGridConstants.filter.SELECT,
condition: uiGridConstants.filter.EXACT,
selectOptions: $scope.filter
};
}
})()
});
}
}
});
}
的代码原有的部分
lovServices.customPropFilterValue(execute_ids)
.then(function (response) {
if (response.id == $scope.columns[i].property.propertyTypeId){
$scope.filter.push({
value: response.value,
label: response.value
});
$scope.columns[i].filter = {
type: uiGridConstants.filter.SELECT,
condition: uiGridConstants.filter.EXACT,
selectOptions: $scope.filter
};
}
});
编辑
我使用的解决方案通过提供@JuanTonina和警告走了,但似乎另一个问题。该i
内then
函数的返回错误值,因为你有一个立即调用的函数表达式,或者IIFE简称
(function (i) { /* note that the lovServices call is INSIDE the IIFE*/
console.log($scope.columns[i].property.propertyTypeId)
// this console log returns correct ids (120, 123, 194)
lovServices.customPropFilterValue(execute_ids)
.then(function (response) {
console.log($scope.columns[i].property.propertyTypeId)
// this console log returns wrong ids (120, undefined, 114)
if (response.id == $scope.columns[i].property.propertyTypeId) {
$scope.filter.push({
value: data.value,
label: data.value
});
$scope.columns[i].filter = {
type: uiGridConstants.filter.SELECT,
condition: uiGridConstants.filter.EXACT,
selectOptions: $scope.filter
};
}
});
})(i)
您需要将'i'作为IIFE参数传递给函数(函数(i){// code})(i )' –
@JuanTonina仍然没有'lovServices.customPropFilterValue(execute_ids) 。然后(功能(响应){ (功能(I){// 我OCDE })(ⅰ); });' – antonyboom
对不起,只是指出你的IIFE只包含'.then'部分。你的代码应该是这样的: 'for(var i ...){(function(i){//循环的全部内容})(i)} 原因是您的变量'i'在使用回调函数之前发生了变化。作为一个方面说明,如果你正在使用es6,做'for(let i = 0 ...)'也解决了这个问题 –