I encountered an issue with AngularJS involving a function that is called before the data array is filled. When the function is invoked in ng-init
, the $scope.bookings
array is not yet populated, resulting in empty data.
My objective is: Retrieve all bookings for a specific bookingType and date, and display them in a <td>
Here is my HTML markup:
Description: The code loops through all bookingTypes
and then iterates over all dates
. While ng-init
is executed correctly for each date, the issue arises with otherBookings
not being populated due to $scope.bookings
being empty at that point.
<tr ng-repeat="bookingType in bookingTypes">
<td>{{bookingType.Name}}</td>
<td ng-repeat="date in dates" ng-init="otherBookings = checkOtherBookings(bookingType.ID, date)">
<span ng-repeat="otherBooking in otherBookings">
<a ng-href="/Bookings/Edit/{{otherBooking.Booking.ID}}"><span >{{otherBooking.Customer.FirstName}}</span></a>
</span>
</td>
</tr>
Here is my JavaScript implementation:
Description: At the start of the BookingsController
, a service call populates the $scope.bookings
array with data, followed by the definition of the $scope.checkOtherBookings()
function below:
BookingService.getAllBookings().then(function(data) {
$scope.bookings = data.data;
});
$scope.checkOtherBookings = function(bookingType, date) {
console.log($scope.bookings);
var newBookingArray = [];
for(var i = 0; i < $scope.bookings.length; i++) {
if($scope.bookings[i].Booking.Type == bookingType) {
var tmpDateFrom = $scope.bookings[i].Booking.DateFrom;
var tmpDateTo = $scope.bookings[i].Booking.DateTo;
if(date >= tmpDateFrom && date <= tmpDateTo) {
newBookingArray.push($scope.bookings[i]);
}
}
}
return newBookingArray;
};
...