The hierarchy of script loading in Angular applications

After years of working with MVC, I recently delved into Angular. Although I am well-versed in JavaScript and HTML, I'm still a beginner in the world of Angular.

I spent hours troubleshooting my app only to realize that the problem was elusive.

The app consists of three files:

index.html

<body ng-app="perica">

        <p>main</p>
        {{ tagline }}
        <a ng-click="logOut();">Logout</a>
        <div ng-view><p>inside</p></div>


    </body>
    <script type="text/javascript" src="../components/angular/angular.js"></script>
<script type="text/javascript" src="../AgularApp.js"></script>
<script type="text/javascript" src="../controllers/AcountController.js">

AngularApp.js

 debugger;
    angular.module('perica', ['ngRoute']).config(['$routeProvider','$locationProvider', function ($routeProvider,  $locationProvider) {

        console.log('in');

            debugger;

            $routeProvider.when('/test', {
            templateUrl: 'views/Account/_Login.html'
    })
    $locationProvider.html5Mode(true);
    }]);

and AccountController.js

   var myApp = angular.module('perica', []);
    myApp.controller('AcountController', ['$scope', function ($scope) {

     $scope.tagline = 'The square root of life is pi!';
            }]);

It's a simple application as you can see.

Based on conventional coding principles, I should load the angular core scripts first, followed by my angular app, and then the angular controls.

However, when I ran the app, Chrome ignored what was defined in AngularApp.js and jumped straight into AccountContoller.js after hitting the first debugger breakpoint inside AngularApp.js.

But To my surprise, reversing the paths - loading AccountController.js before AngularApp.js - resolved the issue without any trouble.

I would appreciate it if someone could provide insight into this perplexing issue. Thanks!

Answer №1

By utilizing...

let myApp = angular.module('perica', [])

... in your AccountController.js, you're actually not loading your pre-existing 'perica' application (which was declared earlier in the loaded AngularApp.js):
instead, you are essentially redefining the perica application.

The correct method to reference your existing module is by using:

angular.module('perica')
                       ^
              no dependencies specified

as opposed to:

angular.module('perica', [])
                         ^
                    including dependencies

The concept behind this is quite straightforward once you understand it: declaring dependencies while "loading" a module results in the creation of that module. Otherwise, you are simply referring to it.

Too Long; Didn't Read (TL;DR): Essentially, you are using a setter twice here and not enhancing your existing module at all.


Here is a functional JSFiddle example (link) showcasing your application in action. I directly loaded AngularJS from the Javascript framework/extensions menu and linked to an external JavaScript resource for angular-route (obtained from cdnjs: https://cdnjs.cloudflare.com/ajax/libs/angular.js/1.4.8/angular-route.min.js).

I essentially combined the contents of both your AngularApp.js and AccountController.js to simulate loading them consecutively.


Please remember that you also need to specify the controller governing your view: I went ahead and enhanced your <body ng-app="perica"> element as follows:

<body ng-app="perica" ng-controller="AcountController">

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

Remove specific symbols entered by a user in a search bar using Angular

Consider this scenario: if I have a search function that looks for hashtags (#) and people (@), how should I handle it when users actually type in those characters, such as: SEARCH: @sally or SEARCH: #trendyTag as opposed to: SEARCH: sally or SEARCH: t ...

Understanding how to utilize variables from Angular within jQuery

I have a variable called room_price and I am looking to utilize it in jQuery. Is there a way to achieve this? $http({ method:'GET', url: '' }).then(function(response){ var roomdata = respons ...

Using Ionic to create a master-detail layout with a side menu

Trying to wrap my head around the master-detail (MD) pattern in Ionic with a side menu. The example code uses 'Playlists' as the master and 'Playlist' as the detail. The states are set up like this: .config(function($stateProvider, $ur ...

Steps for closing the menu by clicking on the link

My issue with the menu on the landing page is that it only closes when clicking the cross button. I want it to close when any link from the menu is clicked. I attempted to add code using querySelector, but it only worked for the home link and not the other ...

Encountering difficulties in accessing state while utilizing async callback functions in React.js

After finding this function on Stack Overflow, I decided to use it in order to update a database and profile information immediately after a user signs up. The function is working as expected, but I am encountering an issue where I can no longer access the ...

Failure to display React component on screen

I have developed a React microfrontend application consisting of two sub-apps rendered through the container/ project. Both sub-apps render perfectly in isolation on localhost:8083. However, when attempting to view them via localhost:8080/dashboard, I am p ...

Ways to verify the contents of an NPM package

After successfully installing the npm package @mediapipe/camera_utils, I am now curious about how to explore the contents within it. Can someone guide me on how to achieve this? ...

Using ExpressJS and Jade to submit a form using the POST method and redirecting to a specified path

I am exploring node, express and jade for the first time and working on a small application that requires users to enter their name and password in a form. The app then redirects them to a path based on their username. Here is the code snippet to achieve ...

Exploring the possibilities of integrating JavaScript with Flash technology

Currently, there is a simple Flash project in development that connects to an RTMP server and streams video and audio from a webcam. The project allows users to create a stream with a specific name. This project also features an input for entering a strea ...

angular material md-input with navigation

We have successfully implemented md autocomplete functionality. However, our specific requirement is to redirect to the corresponding page upon selecting a value from md-autocomplete. <md-autocomplete ng-disabled="isDisabled" md-no-cach ...

Discovering the position of elements in relation to their (grand^N)parent

Among my possessions are elements A and B. B has the ability to exist as a direct child of A, or there may be anywhere from 0 to N elements separating them. It is imperative that I determine how B is situated in relation to A, specifically noting the dist ...

What options are available to enable the user to input information into the v-time-picker component?

I am looking for a solution where users can input digits into the vuetify v-time-picker, while still being able to select the time on the clock. <v-col align-self="center"> <v-menu ref="menuTimeStart" v-model="me ...

Exporting functions using reactjs and babel

I'm currently working on a project that involves using reactjs, transpiled by babel with es2015 and react transforms configured in my .babelrc file. In the initial stages of refactoring, I realized that many of the classes should actually be functions ...

What is the process for extracting the elements of an array fetched from a service in Angular 2?

Currently, I am learning Angular 2 + PrimeNG and going through a quick start project available at the following link: https://github.com/primefaces/primeng-quickstart The project is a CRUD application and it functions flawlessly. The data is neatly displa ...

Center a sans-serif font vertically with exact precision while adjusting the font size

My issue is an expansion of a previous problem I mentioned in another question, which can be found here Vertically align sans-serif font precisely using jquery/css. To summarize: I am aiming to align two divs containing text, with one positioned above the ...

Activate the event when the radio button is changed

Is there a way to change the selected radio button in a radio group that is generated using a for loop? I am attempting to utilize the changeRadio function to select and trigger the change of the radio button based on a specific value. <mat-radio-group ...

What is the best way to send a file object to a user for download?

When working within a route: app.get('some-route', async (req, res) => { // ... } I am dealing with a file object called file, which has the following structure: https://i.stack.imgur.com/ByPYR.png My goal is to download this file. Cur ...

The contrast between FormData and jQuery's serialize() method: Exploring the distinctions

Recently I came across a situation where I needed to submit a form using AJAX. While researching the most efficient method, I discovered two popular approaches - some developers were utilizing jQuery#serialize() while others were opting for FormData. Here ...

An error was encountered in the index.js file within the app directory when running the webpack

Recently, I was told to learn react.js even though my knowledge of javascript is limited. Nevertheless, I decided to dive in and start with a simple "Hello World" project. Initially, when I used the index.js file below and ran webpack -p, everything worke ...

Instructions on removing an HTML element from a div that has the attribute contentEditable

Here is an example of HTML code: <div id="editable" contentEditable="true"> <span contentEditable="false">Text to remove</span> </div> I want to be able to delete the entire span element (along with its text) with just one bac ...