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

Reactivity in Vue.js powered by ES6 classes

I am attempting to create a computed property in Vue.js that is associated with an ES6 class. Here is an example of my Vue instance setup: ... props: ['customClass'], computed: { localClass: { get() { return this.custom ...

Unwrapping nested objects in a JSON array with JavaScript: A step-by-step guide

After trying some code to flatten a JSON, I found that it flattened the entire object. However, my specific requirement is to only flatten the position property. Here is the JSON array I am working with: [{ amount:"1 teine med 110 mtr iletau" comment:"" ...

how to change class on vue function result

I need a way to display the content stored in requestData as li elements. Each list item should have an onclick function that, when clicked (selected), adds a specific value from a reference to an array. If clicked again (unselected), it should remove the ...

Divergent functionality of regular expressions in Internet Explorer and Chrome when handling white spaces

Here is a function that validates input by checking for numbers and no spaces in between: checkInputValidity: function() { var isValid = true; var idNumber = this.getView().byId("iDNumber"); var regex = /^[0-9]+$/; if (idN ...

What is the best location to place AngularJS scope $watch functions?

I am currently facing an issue where I need changes in an AngularJS scope to trigger actions in a model. To achieve this, I utilize the $scope.$watch() method in my item controller and integrate those controllers into directives. The issue arises when an i ...

What is the best way to retain previous values without using an object array to store values in a React state?

My approach involves storing the previous values in an array of objects, where each object represents a key-value pair. For example: [{ActFollow: 'BlN'},{ActSendGift: 'BlY'},{ActSubscribe: 'BlY'}]. However, I aim to transform ...

What significance does #! hold in the context of ui.router?

I am utilizing the Angular ui.router in navigating throughout my application. Typically, the URL should appear like this: http://localhost:8001/#/start However, in my scenario, it appears like this: http://localhost:8001/#!/start What is the significan ...

The properties are not appearing on the screen nor in the React Development Tools

Having difficulties grasping React props and mapping data from an array? Struggling to get the props to show up on your Card component, or display in React dev tools? It's unclear where the mistake lies. Seeking assistance to pinpoint the issue. Also ...

Utilize Angular Js to play a hidden sound in the background without any visible controls

Is there a method to incorporate a background sound without visible controls using Angular JS? I am currently working on an app using Cordova Visual Studio tools. ...

Using the .each() method in jQuery to dynamically assign an attribute to a parent element in JavaScript

I'm new to JavaScript and jQuery and I need help transitioning my code from jQuery to pure JS. Within my HTML, there are multiple parent divs each containing a child div. My goal is to assign a class to both the child and parent elements, with the p ...

Unlocking the Power of Transition: Effortlessly Submitting a Form Post

After the modal finishes fading out, I want my form to be submitted and sent to the email file "refreshform.php". However, currently after the modal fades out, the form does not submit or post anything to the PHP file for sending the email. It simply fades ...

The Facebook login popup has been disabled

My current challenge involves using a Facebook app to authenticate my users. If the user is not logged in to Facebook (which I verify with FB.getLoginStatus()), I provide them with a button to log in. The issue I am facing is that the pop-up for logging in ...

Is there a way to transfer textbox value to ng-repeat in AngularJS?

1) The Industry dropdown menu corresponds with a code textbox. Depending on the selected industry, the code will change accordingly. 2) There is a dynamic feature to add or delete Movie Names and Directors' names. In this table, there are three colu ...

The functionality of the Angular application is impaired when compiled using Phonegap

Background: I have successfully developed an Angular Application that works flawlessly on web browsers. The frontend of the application is built using HTML/CSS/Angular/Bootstrap, while the backend utilizes Web API, making them completely separate entities ...

Guide on filtering a table based on a row value in AngularJS using a button click

I have a button on my interface. Whenever I click the button, I want to refine the data displayed in my table. The table contains elements labeled as market, which can either be "ios" or "android". By clicking the "ios" button, I aim to only display data w ...

Blend jQuery fade in

I have two variables var $aa = $('#Adiv').find('li').has('class'); var $bb = $('#Bdiv'); Both variables should be faded in using fadeIn() $aa.fadeIn(); $bb.fadeIn(); If they have the same action, is it possible ...

Storing JSON information within a variable

I'm currently working on an autocomplete form that automatically populates the location field based on the user's zipcode. Below is the code snippet I've written to retrieve a JSON object containing location information using the provided zi ...

What is the best way to show real-time values using chart js?

Just recently, I've delved into the world of web development and am eager to learn how to integrate chart js for real-time value display. Could anyone offer advice or guide me through the process? var data = []; var temp = []; async f ...

There seems to be an issue with updating the ng-model properly in angular-ui-tinymce

I have encountered a problem where I am attempting to add a DOM node when a custom button is clicked, but the model associated with the textarea is not being properly updated. To illustrate the issue, I have created a plunker as a demo. [https://plnkr.co ...

With vuejs, only one place can control the changing of v-model

Hello, I am currently working on integrating VueJS2 code with Laravel Blade. However, I have encountered an issue with the following VueJS2 code: new Vue({ el:'.add_item_to_price_menu', data:{ percentage:null, }, methods: ...