Exploring a function within a service:
$scope.addPeriod = function(newPeriod) {
if(newPeriod.from !== '' && newPeriod.until !== '') {
var index = $scope.newPeriods.indexOf(newPeriod);
$scope.newPeriods.splice(index, 1);
$scope.setHolidayEditions(newPeriod);
console.log("Check period");
console.log(newPeriod); // state 1: object newPeriod is as expected, it contains holidayEdtions
console.log("Check period copy");
console.log(angular.copy(newPeriod)); // state 2 : object newPeriod is missing the holidayeditions!
$scope.periods.push(angular.copy(newPeriod)); //original code
//some more logic irrelevant to the question
}
}
The issue lies with the angular.copy() method. The structure of the newPeriod object is as follows:
it includes a "from" date and an "until" date, along with an array of magazine objects. In addition, there is the $scope.setHolidayEditions (newPeriod) function, which appends an array of edition objects to each magazine. This function operates correctly, evident from the console output. In the original code, the period is then pushed into an array of periods, which is ultimately displayed on the screen. Presumably, angular.copy() was used to prevent reference issues.
However, the angular.copy() function seems to overlook copying the freshly created editions array within the magazine objects. Is there a rationale for this behavior?
This is essentially what occurs in the service function:
There exists an object named newPeriod, structured like so:
{
from:"02/10/2015",
until:"09/10/2015",
magazines: [
{title:"some title", number:"some number", code:"magazineCode"},
{title:"other title", number:"other number", code:"magazineCode2"}
]
}
post the execution of $scope.setHolidayEditions(newPeriod), the object transforms into:
{
from:"02/10/2015",
until:"09/10/2015",
magazines: [
{title:"some title", number:"some number", code:"magazineCode", holidayEditions:["date","date","date"]},
{title:"other title", number:"other number", code:"magazineCode2", holidayEditions:["date","date","date"]}
]
}
Nevertheless, after the usage of angular.copy(newPeriod), the object reverts back to its initial form:
{
from:"02/10/2015",
until:"09/10/2015",
magazines: [
{title:"some title", number:"some number", code:"magazineCode"},
{title:"other title", number:"other number", code:"magazineCode2"}
]
}
It's perplexing how the angular.copy() operation fails to include the holidayEditions array within the magazines. Any insights on this puzzling behavior?