0
I got the following for
:
for(var i = 0; i < $scope.d.sections.length; i++) {
if($scope.d.sections[i].uid) {
if ($scope.d.sections[i].title != $scope.d.sections[i].oldTitle) {
var uid = $scope.d.sections[i].uid;
var title = $scope.d.sections[i].title;
Page.updateSection(uid, {title: title}).then(function (data){
$scope.d.sections[i].oldTitle = title;
});
}
} else {
if ($scope.d.sections[i].title != 'Add Section') {
var data = {
title: $scope.d.sections[i].title,
pagearticle: $stateParams.uid,
}
Page.addSection(data).then(function (data){
$scope.d.sections[i] = data; //<--------
})
}
}
}
The function Page.addSection
and Page.updateSection
are requests with promises. The problem is this, if the promise takes the value of i within the attribute: $scope.d.sections[i] = data;
It’s gonna be different than what I need, because the for
will be over.
Because I was smart and I did so:
for(var i = 0; i < $scope.d.sections.length; i++) {
if($scope.d.sections[i].uid) {
if ($scope.d.sections[i].title != $scope.d.sections[i].oldTitle) {
var uid = $scope.d.sections[i].uid;
var title = $scope.d.sections[i].title;
var ii = i;
Page.updateSection(uid, {title: title}).then(function (data){
$scope.d.sections[ii].oldTitle = title;
});
}
} else {
if ($scope.d.sections[i].title != 'Add Section') {
var data = {
title: $scope.d.sections[i].title,
pagearticle: $stateParams.uid,
}
var ii = i;
Page.addSection(data).then(function (data){
$scope.d.sections[ii] = data; // <------
})
}
}
I put the value of i
inside ii
. Although it works I think it’s not the best way to do it. So I tried with forEach
:
$scope.d.sections.forEach(function(element) {
if(element.uid) {
if (element.title != element.oldTitle) {
var uid = element.uid;
var title = element.title;
Page.updateSection(uid, {title: title}).then(function (data){
element.oldTitle = title;
});
}
} else {
if (element.title != 'Add Section') {
var data = {
title: element.title,
pagearticle: $stateParams.uid,
}
Page.addSection(data).then(function (data){
element = data; //<---------
})
}
}
})
But the assignment element = data;
does not update the value to $scope.d.sections
.
Is there another way to do this assignment without me having to create a variable for the i
?
What is the code of the functions "updateSection" and "addSection"?
– Haruo