Execute angular.js as a callback function, such as within a $.ajax call

In developing my app, I am primarily working with two key JavaScript files: resources_loader.js and app.js. The role of resources_loader.js is to load some JSON files that are utilized by app.js.

However, the issue arises when considering the sequence in which these scripts should execute. App.js (which encompasses Angular.js functionalities) must run only after resources_loader.js has completed its tasks. Initially, I attempted to incorporate Angular code within the success callback function of resources_loader.js (which employs a deferred), but this approach did not yield favorable results. Below is an excerpt from my index.html file:

<!doctype html>
<html ng-app="myapp">
<body>
    <script src="angular.js"></script>
    <script src="resources_loader.js"></script>
</body>
</html>

Having relocated app.js into resources_loader.js, within the success callback function, whenever I attempt to execute it, Angular throws the following exception: Uncaught Error: No module: myapp.

My assumption is that angular.module('myapp', []) should be executed before the onload event, which does not align with the current implementation.

Furthermore, I am looking to incorporate yepnope.js into my project, like so:

<script "yepnope.js"></script>
<script "resources_loader.js"></script>
<script>
    var loader = load_stuff();
    yepnope({
        test: loader.resolved(),
        yep: ['angular.js', 'app.js', 'foo.js', 'bar.js'],
        nope: ['fail.js']
    });
</script>

The script app.js houses Angular code, and I believe implementing it in this manner enhances performance as it only loads Angular once the necessary resources are available. How can I achieve this effectively?

Answer №1

To initialize your AngularJS app without using the ng-app directive in the <html> tag, you can instead use

angular.bootstrap(document, ['myapp']);
. This will launch your app once all resources are loaded.

var app = angular.module('myapp', []);

app.config(['$routeProvider', '$locationProvider', function($router, $location) {
    $location.html5Mode(true);

    $router
    .when('/', {
        templateUrl: 'some_template.html',
        controller: 'myController'
    });
}]);

// Finally, after setting everything up, trigger the bootstrapping process
angular.bootstrap(document, ['myapp']);

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

Unable to retrieve information from the JSON file

I'm having trouble retrieving data from a JSON file in my script: <script type="text/javascript" src="jquery-1.7.min.js"></script> <script type="text/javascript"> $(document).ready(function () { $('#useruname').ch ...

Is it not recommended to trigger the 'focusout' event before the anchor element triggers the 'click' event?

In a unique scenario, I've encountered an issue where an anchor triggers the 'click' event before the input field, causing it to lose focus and fire the 'focusout' event. Specifically, when writing something in the input field and ...

Exploring the ng-annotate and resolve features within the ui-router framework

Having an issue with my resolve methods not receiving their injected services. Here is a snippet of my code: (function () { 'use strict'; angular.module('sapphire.sample-limits').config(routes); function routes($stateProv ...

What is the best way to identify when a particular character has been entered into the input field?

HTML <div class="form-group"><label class="col-md-4 control-label" for="s1">URL</label> <div class="col-md-4"><input id="url" name="url" type="text" ng-change="checkVal()" ng-model="url" placeholder="" class="for ...

ReactJS: error occurs when trying to fetch data and encountering issues with reading properties

I am currently attempting to initiate an API call (a GET request) in order to download a document. However, I am encountering an error when making the API call: TypeError: Cannot read properties of undefined (reading 'payload') const printPin ...

Seamless Exploration with Google StreetView

Google uses a special effect on StreetView images to transition smoothly between them. You can see an example of this effect in the images below, with the second image showing it being applied. My question is: How can I incorporate this same effect into m ...

The scope of a JS array is being lost in Firebase

The Firebase data structure looks like this: -users --demo1 ---conid:1 -election --election1 ---conRegex:1 --election2 ---conRegex:1 Here is the code to retrieve election1 and election2: var conid; var conRegex; var electionArr = []; if(uidA ...

The implementation of useState is not functioning properly when used within a parent useState function

I am currently working with a Ticket child class where I set the total amount after changing the number of tickets. The issue I am encountering is that the setNumber function doesn't seem to work properly unless the setTotal function is commented out. ...

Application frozen after printing <div>

I'm currently working on a project for a client and I have encountered an issue that I would appreciate some guidance on. My task involves printing the contents of a specific div on the website. After finding a solution in a previous post, I implement ...

Unexpectedly, optimization causing issues on Angular site without explanation

Currently, I am utilizing Angular to construct a front-end website that searches for and showcases information obtained through API requests. Whenever I compile the project into a file bundle for static deployment using ng build, I notice that the resultin ...

Vanilla JavaScript: Enabling Video Autoplay within a Modal

Can anyone provide a solution in vanilla JavaScript to make a video autoplay within a popup modal? Is this even achievable? I have already included the autoplay element in the iframe (I believe it is standard in the embedded link from YouTube), but I stil ...

The "begin" parameter of the Angular limitTo filter appears to be ineffective in Angular version 1.3

Currently, I am attempting to implement a pagination feature on an array of users using Angularjs 1.3. ng-repeat="user in users | filter: searchText | orderBy: 'lastName' | limitTo:pageSize:startPosition track by user.lanId" I specifically want ...

The jQuery pop-up fails to activate on the initial click

I have multiple "Buy Now" buttons for different products. If the button is labeled as "sold-out," it should not do anything, but if it's available, it should trigger a jQuery Magnific Popup. Currently, the popup only opens after the second click becau ...

React is unable to identify the `activeKey` property on a DOM element

First and foremost, I am aware that there have been a few inquiries regarding this particular error, although stemming from differing sources. Below is the snippet of my code: <BrowserRouter> <React.Fragment> <Navbar className=& ...

When you try to combine Angular services, they tend to malfunction

I have two different services that I need to distribute using bower: Categories (categories.service.js) and Product (product.service.js). Both of them are structured similarly, as shown below: (function() { 'use strict'; angular .modul ...

Extend JavaScript capabilities for window.print() function to automatically include backgrounds

I am looking to add a special magical property to my Print this Page button. This property will automatically enable the default unset option (shown in the picture) which is to print the backgrounds of div colors and background images. <a href="#" oncl ...

Angular - Error: Cannot read property 'publishLast' of undefined

My goal is to prevent multiple requests from being created when using the async pipe. I am facing an issue with a request to fetch a user from the API: getUser() { this._user = this.http.get<User>(environment.baseAPIUrl + 'user') ...

I'm interested in exploring different database implementation patterns in JavaScript. What kinds of approaches can I consider?

As someone who is relatively new to exploring JavaScript, I have been immersed in experimenting with a node test app and MongoDB. I am eager to delve into the database aspect of the app but finding myself uncertain about the most commonly used patterns in ...

JavaScript array loading failed for the C# web service

I am encountering an issue with a JavaScript object in my application that contains an array object, which is a collection of objects with two properties (Name, Value) on the server-side. Despite my efforts, when the code reaches the C# web service, the C ...

Combine the values in the array with the input

I received some data from the back-end which is being written to a form, and it's in the form of an array of objects Below is the code snippet: this.companyDetailsForm = new FormGroup({ directors : new FormControl(response?.companyDirectors) ...