Loading Angular's UI-Router view twice

My Angular application is using Angular UI-Router for routing. Here is the configuration I have set up:

var routerApp = angular.module('routerApp', ['ui.router']);

routerApp.config(function($stateProvider, $urlRouterProvider) {

$urlRouterProvider.otherwise('/home');

$stateProvider

    // HOME STATES AND NESTED VIEWS ========================================
    .state('home', {
        url: '/home',
        templateUrl: 'partial-home.html',
           controller : function($scope,$state){
            $scope.$on('$viewContentLoaded', function(){
              console.log("home content loaded",$state.current);
            })
          }
    })

    // nested list with custom controller
    .state('home.list', {
        url: '/list',
        template: 'I am using a list.'
    })

    // nested list with just some random string data
    .state('home.paragraph', {
        url: '/paragraph',
        template: 'I could sure use a drink right now.'
    }) 

});

In partial-home.html, I have written the following:

<div class="jumbotron text-center">
  <h1>The Homey Page</h1>
  <p>This page demonstrates <span class="text-danger">nested</span> views.</p>

  <a ui-sref=".list" class="btn btn-primary">List</a>
  <a ui-sref=".paragraph" class="btn btn-danger">Paragraph</a>

</div>

<div ui-view></div>

When executing the app in the browser and opening the route

/home

The browser console shows "home content loaded" once. Clicking on the list link changes the address bar to

/home/list

and the console logs once again.

However, if I refresh the browser tab at that time (when the route is home/list), the console logs twice. Can anyone help me understand why this is happening?

Answer №1

These views are nested within each other, which is why you are seeing two messages in your console after reloading the page. When you initially enter /home, the home state is loaded. Then, when you navigate to /home/list, only the home.list view needs to be loaded since the home state is already present. However, when you reload the page, both the home and home.list states need to be loaded again, resulting in two messages.

Additionally, it seems like you may have used a ui-view inside the home template, causing the child and parent scopes to overlap. This means that events triggered by either the child or parent scope will be listened to, leading to the event being called twice in this scenario.

Answer №2

When reloading the page for home.list, the view of the home controller is first initialized, followed by the view of the list controller, resulting in $viewContentLoaded being triggered twice.

It seems like ui-view is used inside the home template, causing the child and parent to share the same scope. As a result, both the child's and parent's scopes are listened to for the event, leading to it being called twice.

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

Is it possible to utilize a variable while assigning an element id through a JavaScript function?

Currently, I am in the process of learning JavaScript and have come across a scenario that has left me uncertain. I am attempting to utilize a variable in a particular situation and am unsure if it will work as expected. I am looking to assign a unique id ...

What causes the HTML element's X position value to double when its X position is updated after the drag release event in Angular's CDK drag-drop feature?

I am facing a challenge with an HTML element that has dual roles: Automatically moving to the positive x-level whenever an Obsarbalve emits a new value. Moving manually to both positive and negative x-levels by dragging and dropping it. The manual drag a ...

Deciphering date and time strings in C3

Can someone point me in the direction of documentation explaining how C3 parses datetime strings? It doesn't appear to follow moment.js format, and I'm having trouble finding clear guidance on this. For example, if I have a datetime string like 2 ...

Choose the initial unordered list within a specific division through Jquery

In a div, there is a ul. Inside a li, there is another ul. The task is to select only the first ul inside the div using jQuery. The HTML markup: <div class="parent"> <div class="clearfix"> <div class="another-div"> <ul cl ...

Get help with managing your events using JQuery and PHP Calendar

Currently undertaking a project that involves the creation of a calendar, where by clicking on any date of the year, it will redirect to another page to input specific information. My issue lies in the fact that I have been unable to locate a basic calenda ...

Instructions on accessing environment variables within a Grunt configuration file

My Angular application operates in three different environments: Development, Staging, and Production. When Heroku builds the application based on my build script, a Gruntfile includes a release task that uglifies the code. Heroku executes the command Gr ...

Utilizing Translation (i18n) in AngularJS Controller to Implement Popups

I'm currently working on an AngularJS app and need to implement i18n. Everything is running smoothly except for error handling, specifically with utilizing translations in controller for popups. Here is a snippet of my controller: function showError ...

Issue with timebox filtering in customapp.js for Rally SDK 2

I am interested in creating a timebox filtered app and found an example at However, when attempting to run this on a custom HTML page, I encountered the following error: Failed to load resource: the server responded with a status of 404 (Not Found) on th ...

Issues encountered when using .delay() in conjunction with slideUp()

Issue: The box is not delaying before sliding back up on mouse out. Description: Currently, when hovering over a div with the class ".boxset" called "#box", another div "#slidebox" appears. Upon moving the mouse away from these two divs, #slidebox slides ...

Select three random items from a string array list along with their corresponding indexes using TypeScript in Angular

Consider this example: I am working with a string array const groceries = [ 'milk', 'coriander', 'cucumber', 'eggplant', 'carrot', 'brinjal', 'on ...

Leveraging Async/Await in NodeJS within Array.map alongside an 'if' condition

Within my code, there is a recursive function that iterates over an object. It specifically searches for keys labeled subcomponent (always containing an array) and executes an asynchronous task on each child within subcomponent, using the output to replace ...

Additional headers are included in the Access-Control-Request-Headers

I have been struggling to include a customized header in my angular js GET request like so: $http({ method : 'GET', url : s, headers : { "partnerId" : 221, "partnerKey" : "heeHBcntCKZwVsQo" } ...

How can I execute a Python script on an HTML webpage by clicking a button?

Below is the HTML code I have written: <script> function goPython(){ $.ajax({ url: "MYSCRIPT.py", context: document.body }).done(function() { alert('finished python script');; ...

Convert an HTML table into a PDF file by generating a blob

Can anyone help me figure out how to export a PDF file from AngularJS? I've already successfully exported an Excel file. Here is the code for exporting Excel: In view.html <button ng-click="vm.exportData()" class="btn btn-info"><i class="g ...

Monitor Socket IO for client disconnection events

I am facing an issue where I need to identify when a user loses connection to the socket. It seems that socket.on("disconnect") is not triggering when I simply close my laptop, leading to the ajax call not executing to update the database and mark the us ...

Is there a way to verify that a form field has been completed?

Currently, I am grappling with a method to clear a field if a specific field is filled in and vice versa. This form identifies urgent care locations based on the information provided by users. The required entries include the name of the urgent care facil ...

Steps for disabling a specific input type in HTML

I have created a web application with CRUD functionality. My current objective is to differentiate the Add and Edit functions. Here's what I mean: When a user invokes the Add function, they are required to provide an ID, while the Edit function should ...

Using jQuery to choose options and change the background color

Hey there, I have a select box below: <select id="events"> <option value="1" style="background-color:green;">Event 1</option> <option value="2" style="background-color:yellow;">Event 2</option> <option value="3 ...

Unresponsive jQuery Ajax JSON Request

I am working with a basic Ajax function: insertInto = function(){ console.log("Hello "); var power = $("#power").val(); var vehicle = $("#vehicle").val(); var sendData = { "power": power, "vehicle": vehicle }; $.ajax({ type: ...

transforming JSON key names by associating them with their corresponding JSON values and modifying the key names

My challenge lies in converting a JSON string from one format to another. The initial format is: [ { clientIDs: "WELL #6", analyteIDs: [ "7440-62-2", "7440-28-0" ] } ] ...