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

Creating multiple instances of an object

When using Javascript, I am trying to create an object in the following way: var testObject = { value: "this is my initial value", setup: function() { value: "foo" } }; Now, my goal is to instantiate this object and have different val ...

Verify whether the element retains the mouseenter event after a specified delay

I recently implemented some blocks with a mouseenter and mouseleave event. <button onMouseEnter={this.MouseEnter}>hover</button> MouseEnter(e) { setTimeout(() => { // Checking if the mouse is still on this element // Pe ...

AngularJS: Leveraging Devise with Several Models

I have a Rails application with two different user models that represent distinct roles (no Single Table Inheritance - each model is separate). I am considering transitioning to AngularJS for the frontend. I want to determine the most effective way to str ...

Fill the dropdown menu with JSON keys

My challenge involves working with an array containing objects, which are sent to the client via a node.js server integrated with mongodb. I need to extract all keys/fields from the object (such as name, surname, telephone) without their values (for exampl ...

Guide for populating the chosen item in a combobox when the form control option has various parameters

I need help populating the selected saved item into the form control. <select class="form-control"> <option data-parameter-id="685" data-parent-id="1052" data-aggregation-id="null" data-aggregation-parameter="null">ABC</option> & ...

Reset the child JSP page to its original appearance

Displayed below is a JSP page: <div id="tabs-7" style="width: 100%;"> <form:form id="deviceForm" name="" modelAttribute="" enctype="multipart/form-data"> <div class="inputWidgetContainer"> <div class="inputWidget"> <table> ...

Using Django, CSS, and Javascript, create a dynamic HTML form that shows or hides a text field based on the selection

How can I hide a text field in my Django form until a user selects a checkbox? I am a beginner in Django and web applications, so I don't know what to search for or where to start. Any guidance would be appreciated. Here is the solution I came up wi ...

After making changes to the message converters, Jackson and Spring web are encountering issues with deserializing unquoted strings

In my spring controller method, I am accepting a String as the entire RequestBody like this: @RequestMapping(method=RequestMethod.POST) public @ResponseBody DTO method(@PathVariable("userId") long userId, @RequestBody String page) { // Co ...

What is the solution for the error "BREAKING CHANGE: webpack < 5 used to automatically include polyfills for node.js core modules"?

I am trying to use the "web3" and "walletconnect/web3-provider" package in a Vue & Laravel 8 project. I have installed it using the npm i --save web3 @walletconnect/web3-provider command and then added the following code to import into ...

There was an issue encountered while attempting to add concurrently to the package.json

Bundle of scripts in package.json "scripts": { "begin": "node back-end/server.js", "serve": "nodemon back-end/server.js", "client-initiate": "npm start --prefix front-end", ...

A guide to selecting the bookmark with a URL that is on a currently opened page

To gain a clearer understanding of my goal, follow these steps: Open the Chrome Browser and go to a URL, such as https://www.google.com. Once the page loads, locate and click on the bookmark labeled "ABC", which contains the URL ({window.open('/ ...

Tips for setting a jQuery variable equal to the value of a JSON object

When I try to assign courseid and batchid as defaults using defaultValue => defaultValue: courseid and defaultValue: batchid, the values are not being saved correctly in my database. $(document).ready(function() { var courseid = null; var bat ...

Are jQuery plugins offering accessible public functions?

I am currently working on enhancing the functionality of a jQuery plugin. This plugin serves as a tag system and utilizes autocomplete provided by jQuery UI. Presently, there is no direct method (aside from parsing the generated list items) to determine ...

Embracing the Unknown: Exploring Wildcard Values

I have a code snippet below that has a wildcard * in it. I'm looking for suggestions on how to make the * accept any number. Any thoughts on this? $('body').on('click', '.custom_295_*-row', function(){ var href = "htt ...

What's better in React: using pure components or non-pure components? Is it okay to fetch data in componentDidMount or

Exploring React in Meteor has led me to observe two distinct approaches... Take the meteor leaderboard example, where a list of players displays their names and scores. The pure approach involves fetching all players and passing them into the playersList ...

Tips for testing nested HTTP calls in unit tests

I am currently in the process of unit testing a function that looks like this: async fetchGreatHouseByName(name: string) { const [house] = await this.httpGetHouseByName(name); const currentLord = house.currentLord ? house.currentLord : '957'; ...

The search functionality for the MongoDB module is not functioning properly within my Next.js application

Working on my nextjs application, I have encountered an issue with using the mongodb node module to find all documents in one of my collections. Despite successful usage of .findOne and .updateOne for other pages like login and password reset, when I use . ...

Exploring the Integration of Google Maps and Angular Google Places in Angular 2

On my webpage, I am utilizing two components simultaneously: and angular2-google-map-auto-complete from https://www.npmjs.com/package/angular2-google-map-auto-complete. To set the Angular maps key, I have defined it as follows: AgmCoreModule.forRoot({ a ...

Exploring methods for testing an HTML page that utilizes jQuery for DOM manipulations

Recently, I was tasked with creating an HTML page that utilized jQuery DOM manipulations. For instance, upon clicking the submit button, a success or error message should be displayed. Testing these functionalities is something I'm familiar with in An ...

Switching classes in real time with JavaScript

I'm struggling to understand how to toggle a class based on the anchor text that is clicked. <div> <a id="Menu1" href="#">Menu</a> <div id="subMenu1" class="subLevel"> <p>stuff</p> </div> <div> <a i ...