Currently, I am working with the Angular UI grid library and facing an issue while populating a custom dropdown filter. This filter is only meant to be applied to specific columns, which is why I have implemented a for loop to dynamically access these columns. For each specific column, I make a request to the API using my Angular services to fetch values for the filter. If the response is successful, I compare the property id of each column with the returned data id and then populate the filter value.
The problem arises within the then
function, as my IDE displays a warning
mutable variable is accessible from closure
and nothing seems to work inside the then
function.
I have come across various discussions on this platform and learned that I need to execute a self-invoking function, but even that solution doesn't seem to work for me.
So, where exactly am I making a mistake? Your help is greatly appreciated.
Here is the code snippet in question:
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
};
}
})()
});
}
}
});
}
Here is the original part of the code for reference:
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
};
}
});
EDIT
After implementing the solution provided by @JuanTonina, the warning message disappeared, but a new problem surfaced. The i
variable within the then
function returns an incorrect value.
(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)