Function executed prior to populating $scope array

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;
};
...

Answer №1

If you want to return a promise within the checkOtherBookings function, AngularJS parser will handle it automatically. Your code should be structured like this:

$scope.checkOtherBookings = function(bookingType, date) {
    var deferred = $q.defer();
    $scope.$watch('bookings', function(bookings) {
        if (!bookings) return;
        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]);
                }
            }
        }

        deferred.resolve(newBookingArray);
    });
    return deferred.promise;
};

A demonstration of this technique can be found in this plunker: demo link.

Update:

The method mentioned above is suitable for AngularJS 1.0.x. In AngularJS 1.2RC (and potentially 1.1.x), the handling of functions returning promises differs. In these versions, the parser does not return the promise but instead immediately returns the internal $$v of the promise, which is undefined until resolved. If you are using version 1.2, it is recommended to remove ng-init and try one of the alternative approaches below.

Approach #1:

$scope.$watch('bookings', function(bookings) {
    if (!bookings) return;
    // Filter bookings and set $scope.otherBookings = filteredList
});

Approach #2:

$scope.getOtherBookings = function() {
   // Return filter list here
}

<span ng-repeat="otherBooking in getOtherBookings()">

Approach #3:

<span ng-repeat="otherBooking in bookings | customFilterFunction">

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Generating PDF files from HTML documents using Angular

I am currently working on an Angular 11 application and I have a specific requirement to download a PDF file from a given HTML content. The challenge is that the HTML content exists independent of my Angular app and looks something like this: < ...

Guide to dynamically assigning the id attribute of an HTML element using angularjs (1.x)

Given an HTML element that is a div, what is the method to assign a value to its id attribute? The value should be a combination of a scope variable and a string. ...

The integration of express and cors() is malfunctioning

Currently, I am developing a React application and facing an issue while trying to make an API call to https://itunes.apple.com/search?term=jack+johnson In my project, there is a helper file named requestHelper.js with the following content : import &apo ...

What is the process for sending body data through Swagger in a Node.js/Express environment?

Below is the configuration for my swagger: /** * @swagger * /api/addData: * post: * consumes: * - text/html * produces: * - text/html * parameters: * - name: author * in: body * required: true * ...

I'm looking to transfer my stringified object into the HTML body. How can I achieve

When sending an HTML file to a client using the res.write() method, I also need to include an object within the HTML. However, when I stringify the object and add it along with the HTML, the JSON object ends up outside of the HTML structure. I require the ...

NodeJs causing issues with reloading AngularJs routes

I was able to successfully create a sample app by following a few examples, but I've encountered an issue that I'm struggling to resolve. In my Angular app, the routes work fine like this: - http://localhost:8888/#/login works However, when I re ...

Is there a way to ensure that my function does not return undefined and instead returns a specific value?

Currently, I am facing a roadblock while attempting to conquer the Rock-Paper-Scissors challenge proposed by The Odin Project. Some confusion arises as my function playRound seems to be returning undefined when executed. Any insights or assistance in res ...

Maintaining form data while dynamically including more instances of a <div> element to the form

I am currently developing a SpringMVC Webapp with a view that contains a dynamic form. The dynamic elements of the form are listed below: At the moment, I am passing the variable ${worksiteCount} from my controller to the view (stored in my portlet sessio ...

A guide to handling deep updates with subdocuments in Mongodb/Mongoose

In this scenario, I am looking to utilize mongoose. Consider a Schema structured like the following: const userSchema = new Schema({ name: { first: { type: String, required: true }, last: { type: String, required: true }, }, email: { type: S ...

ParcelJS takes a unique approach by not bundling imported JavaScript libraries

My NodeJS app, which is a Cloudflare Worker, seems to be having trouble with bundling the 'ping-monitor' dependency. In my main typescript file (index.ts), I import the handler module and the first line reads: const Monitor = import('ping-m ...

What is the best way to handle an OR scenario in Playwright?

The Playwright documentation explains that a comma-separated list of CSS selectors will match all elements that can be selected by one of the selectors in that list. However, when I try to implement this, it doesn't seem to work as expected. For exam ...

Analyzing the functionality of Express with Mocha and Chai

Currently facing an issue with testing my express server where I am anticipating a 200 response. However, upon running the test, an error occurs: Test server status 1) server should return 200 0 passing (260ms) 1 failing 1) Test server statu ...

issue occurred when executing the command "grunt serve:dist"

I utilized the mean stack seed by following this link: https://github.com/angular-fullstack/generator-angular-fullstack However, when attempting "grunt serve:dist," I encountered the following error: Running "ngAnnotate:dist" (ngAnnotate) task >> 2 ...

Wiki experiencing issues with NodeJS HttpGet functionality

Goal Retrieve the HTML content of a Wiki Page. Introduction In an attempt to fetch the HTML of a Wiki page () for data parsing purposes, I am utilizing NodeJS and its HTTP Request methods. Code Snippet Below is the simple code snippet that accesses th ...

What is the best way to determine the width of a div within a window that has been rendered using React?

I'm working on a task where I need to determine the size of a div (with CSS width set to 100%) and adjust the zoom factor of a component based on this size. The challenge arises during the initial run of the application when the div has not yet been c ...

The TypeScript compiler generates a blank JavaScript file within the WebStorm IDE

My introduction to TypeScript was an interesting experience. I decided to convert a simple JavaScript application, consisting of two files, into TypeScript. The first file, accounts.ts, contains the main code, while the second one, fiat.ts, is a support f ...

"The Bootstrap framework in MVC is throwing an error message stating that '$.notify' is not recognized as

I'm having trouble getting a notify to show up when my ajax function completes successfully. I've checked my code and everything seems fine, but for some reason the notify isn't working as expected. When I checked the Chrome console, I found ...

By unplugging the # from the URL, I suddenly found myself unable to directly access my links

After deciding to remove the # symbol from my URLs in order to make them more user-friendly, I followed a tip from a question on Stack Overflow titled Removing the fragment identifier from AngularJS urls (# symbol). However, upon trying to directly access ...

Troubleshooting HTML/JavaScript with JSP and JSTL: iPhone only displaying the first option in select dropdown, rather than the selected option

My HTML includes a <select> element: <select id="mySelect"> <option value="1">1</option> <option value="2">2</option> <option value="3">3</option> <option value="4">4</option> ...

Display a pop-up when hovering over a layer with react-leaflet

I am attempting to display a popup when hovering over a layer in react leaflet. Utilizing GeoJson to render all layers on the map and onEachFeature() to trigger the popup on hover, I encountered an issue where the popup only appeared upon click, not hover. ...