Endless AngularJS loop using ng-view

I recently started experimenting with AngularJS for a new project I am working on, but I have encountered a problem when dealing with routes and views.

For the sake of simplicity, I have minimized this example to its basic form, yet the issue persists. This example simply fetches the index.html page from the server, which then loads Angular and other necessary files.

index.html

<!doctype html>
<html lang="en" ng-app="main">
    <head>
        <meta charset="utf-8" />

        <link rel="stylesheet" type="text/css" src="css/style.css" />

        <script type="text/javascript" src="js/ext/angular.min.js"></script>
        <script type="text/javascript" src="js/ext/angular-route.min.js"></script>
        <script type="text/javascript" src="js/main.js"></script>
        <script type="text/javascript" src="js/test.js"></script>

        <base href="/ui/">
    </head>
    <body>
        <div ng-view></div>
    </body>
</html>

main.js

(function() {
    var app = angular.module('main', ['ngRoute', 'test']);

    app.config(['$routeProvider', '$locationProvider', function($routeProvider, $locationProvider) {

        $routeProvider
            .when('/test', {
                templateUrl: 'html/test.html',
                controller: 'TestCtrl'
            })
            .otherwise({
                redirectTo: '/test'
            });

        $locationProvider.html5Mode(true);
    }]);
})();

test.js

(function() {
    var app = angular.module('test', []);

    // get hierarchy
    app.controller('TestCtrl', ['$scope', function($scope) {

        alert('here');

    }]);
})();

test.html

<div>FooBar!</div>

The alert keeps popping up endlessly, and I can't figure out why. I have looked at other examples where ng-view and routing are utilized in the same manner, so I am uncertain about what is causing the issue...

Answer №1

A while back, I encountered the same issue. My suggestion is to utilize either firebug or a network control tool within the browser's developer tools panel. This will allow you to view the server requests for resources and ensure that the test.html file is being requested and retrieved properly. It appears that only the index.html file is being retrieved, causing the loop.

It's possible that you need to include a "/" before the templateUrl value "/html/test.html" in order to correctly locate this resource.

My recommendation is to localize the test.html resource properly. Hopefully, this suggestion will aid you in resolving the issue.

Answer №2

Today, March 2016, I encountered a frustrating issue with an infinite loop caused by ng-view in my HTML (specifically index.html, the initial page loaded).

The culprit turned out to be a simple oversight in my route provider configuration in app.js:

angular.module('myapp',['ngRoute'])
    .config(function($routeProvider) {
      $routeProvider
      .when('/', {
          templateUrl:'/index.html',
          controller:'MyAppCtrl'
      })

The problem was that since index.html was being loaded initially and the URL was '/', each time the code for when '/' was invoked, it would load index.html again, creating an endless loop. The solution? Simply avoid setting index.html as the templateUrl for the '/' route and ensure that the template does not include <div ng-view></div>.

Answer №3

Check out my approach in action, see the demo here

Solution

.config(['$routeProvider', '$locationProvider',function($routeProvider, $locationProvider) {
$routeProvider
    .when('/page1', {
        template: '<div>content one</div>',
        controller: 'page1Ctrl'
    })
    .when('/page2', {
        template: '<div>content two</div>',
        controller: 'page2Ctrl'
    })
    .otherwise({
        redirectTo: '/page1'
    });

    $locationProvider.html5Mode(true);

}]);

Answer №4

After some troubleshooting, I successfully resolved my issue. I ended up accepting sergio's solution because it was the closest to what helped me figure out the problem - my app was requesting the html file from the application server, which defaulted to returning the index.html file. Since there was no associated action for the html request, it defaulted to serving the index.html instead of the test.html file.

Once I made a simple change to the url and retrieved the html file from the web server instead, everything started working perfectly. If only I had taken a moment earlier to carefully think through the situation, the solution would have been quite obvious.

I appreciate all the responses that were provided!

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

Utilize the "incorporate" feature to include any string within an array

I am currently working on improving the search function in my application. This particular search function takes input from a search bar and is designed to handle multiple search terms. For example, it should be able to handle queries like "javascript reac ...

I've been stuck on this for the past hour, trying to figure out why /js/bootstrap.min.js can't be located

I'm having an issue with the code in base.html while trying to create a bootstrap starter template. I copied it from bootstrap but when I run it, I get an error related to /js/bootstrap.min.js. Can someone help me figure out what's wrong? Thank y ...

What are the reasons for passing a global variable to a function?

Is there a difference between the two ways of writing this code? First Method: (function(i) { // Manipulate i here }(global_variable)) Second Method: (function() { // Manipulate global_variable here }()) What's the reason for passing a gl ...

Need a tool for validating forms?

I am currently facing some confusion with the UI Validation plugin that we are using. Within our application, we employ Spring MVC, Jquery & Bootstrap. As we delve into UI development, we have encountered uncertainty in selecting an appropriate Validation ...

My Angular JS http.get request is failing to reach the specified URL

While working with AngularJS to integrate RESTful web services into my website, I am encountering an issue where I am consistently receiving errors instead of successful responses. I have been stuck on this for the past three days and any assistance would ...

The display of data attributes is not being rendered correctly

Check out the fiddle I'm currently working on: http://jsfiddle.net/7Z8wY/9/ The HTML section looks like this: <div class="container"> <div class="right"> <div id="cityList" class="inner-table"></div> </div> ...

Styling for older versions of Internet Explorer (IE10 and earlier)

Could it be true that IE 10, 9, and others no longer support conditional statements? Is it also accurate to say that JQuery does not support the browser object above version 1.9? I am facing an issue with CSS rendering differently in Chrome and IE. A Goog ...

Interface-derived properties

One of the challenges I'm facing is dealing with a time interval encapsulation interface in TypeScript: export interface TimeBased { start_time: Date; end_time: Date; duration_in_hours: number; } To implement this interface, I've created ...

Is there a navigation feature in VueJS that functions similarly to React Router?

I am currently working on enhancing the navigation experience of an existing vueJS application that utilizes Vue Router. When working with React, I typically structure breadcrumbs in the following manner: <Breadcrumbs> <Route path="/users&q ...

Sending auth0 token as a parameter in $http.get request in Angular

I am encountering difficulties when trying to attach the auth0 token to a http.get request for an API that requires the token. The token is generated upon user login and stored in the browser's local storage, which is functioning properly. The challen ...

Which specific file name patterns does npm publish consistently exclude?

When using the npm publish command, the documentation mentions that certain files will not be included in the package unless explicitly added to the "files" list in package.json or un-ignored with a specific rule. What exactly are these "certain patterns"? ...

States are consistently maintained in React and do not impact the rendering process

I am keeping track of a state value by declaring it like this: const [count, setCount] = useState(0); To increment the count: const incrementCount = () => { setCount(count + 1); } I use this function in a loop to iterate through an array, exec ...

Utilizing an imported variable beyond a component function within React useEffect: A comprehensive guide

I'm encountering a problem while trying to utilize the imported variable likedImages within a useEffect hook in a React component. When I include likedImages in the dependency array, I receive a warning indicating that it is an unnecessary dependency ...

Modify the text on a button using vanilla JavaScript

Although it may seem like a simple question, I am struggling to change the text on my button. The code for my button in the web browser console is: <button class="nav-link active" id="coholder-tab" data-toggle="tab" data-t ...

Using the XMLHttpRequest object for AJAX file uploads that are compatible with Internet Explorer 9

Seeking help with uploading a file using ajax. The current code works on all browsers except for i.e 9 and older versions. I need to find a solution that will also work on i.e. Some suggestions have been to use an iframe, but I don't see how that res ...

Exploring the wonders of accessing POST request body in an Express server using TypeScript and Webpack

I am currently working on a Node and Express web server setup that utilizes Webpack, along with babel-loader and ts-loader. Let's take a look at some key portions of the code: webpack-config.js: const path = require("path"); const nodeExte ...

Oops! Issue: The mat-form-field is missing a MatFormFieldControl when referencing the API guide

I included the MatFormFieldModule in my code like so: import { BrowserModule } from '@angular/platform-browser'; import { NgModule } from '@angular/core'; import { AppRoutingModule } from './app-routing.module'; ...

Using CSS on a randomly selected div that is chosen after dividing the main div each time it is clicked

Imagine a square box displayed as a "div" element. When you click on it, it splits into an n x n grid with each square having a random background color. However, the issue I am encountering is that I want to apply additional CSS to each of these randomly c ...

ng-grid featuring popup editing functionality

Utilizing the ng-grid="gridOptions" allows me to showcase data in my application. Below is the code snippet from my app.js file: $scope.gridOptions = { data: 'myData', enableCellSelection: true, enableCellEdit: true, enableRowSelection ...

Leveraging the capabilities of Express functions on the client side through the require method in Node.js

Trying to access the configuration variables set in the file named test.js which contains -- var aws = require('aws-sdk'); exports.connect = function(){ return aws; } Now, I am attempting to access it upon an OnClick event taking place ...