Angular UI-Router has a quirk where it may execute a controller twice upon loading if it is defined within the

Every time I run the code in my controller, it seems to be executed twice, resulting in duplicate outputs in the console.log window of Chrome Dev Tools.

questions.html

<div ng-controller="questionController as vm"> </div>

questionController.js

var questionController = function($location, questionService, $env) {
    var vm = this;
    console.log('in the controller')  // this runs twice 
}

app.js

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

        var viewBase = '/apps/src/views/';

        $urlRouterProvider.otherwise("/");

        $locationProvider.hashPrefix(''); // get rid of ! was getting #! 

        $stateProvider
            .state('questions',
            {
                url: "/questions",
                templateUrl: viewBase + "questions.html"//,
                //controller: "questionController"
                //views: {
                //
                //}
            });


    }]
);

I have noticed that by commenting out the controller: "questionController" in the route, the duplication issue is resolved.

Last year, when I used ui-router, I never faced any problems when using the controller:.

Could there be a compatibility bug with some new version combinations?

After attempting to resolve the issue but not displaying data

I am incorporating ui-grid

 <!--<div ng-controller="questionController as vm">-->

       <div ui-grid="{ data: vm }" class="grid"></div>

  <!--</div>-->

Note that I have commented out the div with the ng-controller attribute.

  var vm = this
  var promise = questionService.getAllQuestions();

    promise.then(function(response) {
        vm.myData = response;
        console.log('questionCtrl promise data', vm.myData);
    });

The console.log statement successfully displays the data.

Successfully Resolved

It appears that I had to make the following changes

route

     controller: "questionController",
     controllerAs : "vm"

OR

      controller: "questionController"

Then

 <div ui-grid="{ data: vm.myData }" class="grid"></div>

Answer №1

The reason for this behavior is due to the fact that you are adding the controller in your $stateProvider and also including it in the template itself with the following code:

<div ng-controller="questionController as vm"></div>

To resolve this issue, you should remove the ng-controller directive from your HTML.

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

Unable to Click on Selenium Element

When a link is clicked on a website, the URL remains unchanged but a popup appears on the screen containing elements that can only be accessed after running driver.switchTo().defaultContent(). To access these elements, I have used a javascript executor com ...

Unlocking the Secret: How to Bind a Global Touch Event Handler in Angular 4 to Prevent iOS Safari Page Drag

The issue at hand is that within my Angular 4 application, there is a D3.js chart that relies on user touch input for dragging a needle to a specific value. The drag functionality is triggered by 'touchstart', while the registration of the final ...

Reducing div size when clicked - Using JQuery version 1.9

I am looking to make a specific div shrink in size, while keeping all the data visible, each time a user clicks on a certain icon with the class legend-icon. For example, I want the div with the ID #Chart to shrink when clicked. This is the HTML code: &l ...

Discovering the total number of tickets based on priority in an array with Javascript

I have the following data set { agent_id:001, priority:"High", task_id:T1 }, { agent_id:001, priority:"High", task_id:T1 }, { agent_id:001, priority:"Medium", task_id:T1 } { agent_id:002, priority:"High", task_id:T1 ...

Issue encountered: NPM error, unable to find solution for resolving dependency and addressing conflicting peer dependency

I am facing difficulties deploying my project on netlify due to NPM errors. Below are the dependencies: "dependencies": { "@angular/animations": "~15.1.1", ... (list of dependencies continues) ...

Adjust the size of the image as needed in order to fit within a container of fixed

Is there a clever way to use CSS and/or JavaScript/jQuery to adjust the size of images only when necessary for them to fit within a fixed-height container alongside the remaining content? Upon reviewing the images in the 'new this week' and &apos ...

What is the best way to execute two JavaScript functions within an inline onclick event?

I am currently working on the following code snippet: <script> function delay (URL) { setTimeout( function() { window.location = URL }, 2000); }</script> And then I have the following within the <body> element: <img src="small_rabbi ...

Steps to send an asynchronous AJAX request to the server-side within the JQuery validation plugin using the addMethod() function

Currently, I am in the process of developing my own framework using the JQuery validation plugin to validate CRUD forms both client-side and server-side. It is crucial that these forms are not static but rather created dynamically using "handlebar.js". Fo ...

Can a node.js file be exported with a class that includes IPC hooks?

[Node.js v8.10.0] To keep things simple, let's break down this example into three scripts: parent.js, first.js, and second.js parent.js: 'use strict'; const path = require('path'); const {fork} = require('child_process&apo ...

Expanding a list in AngularJS: Implementing a scrollbar for a seamless user experience

I need assistance in creating a layout using AngularJS and angular-material that includes a vertical scrollbar when necessary: <div layout="column"> <div> <!-- Occupies 80% of window browser --> <md-list> <md-l ...

Webhost sending information to Windows sidebar gadget

Is there a way to showcase a list of information from a web host on a Windows sidebar gadget without using iframes? I've heard about using JavaScript AJAX (XmlHttpRequest) for this purpose, along with a refreshing function. Can anyone provide some gui ...

Insert half a million records into a database table using JavaScript seamlessly without causing the webpage to crash

I am facing an issue with my report system where running a single report query results in over 500,000 rows being returned. The process of retrieving the data via AJAX takes some time, but the real problem arises when the browser freezes while adding the H ...

Tips for integrating highcharts plugins with highcharts-vue (highcharts vue wrapper)

Currently, I am utilizing the Vue wrapper for Highcharts called highcharts-vue(https://github.com/highcharts/highcharts-vue). However, I am facing an issue where I need to detect the event of a right mouse click (contextmenu) on the chart. To address this, ...

React component slider encountering issue of 'undefined property style reading'

I attempted to develop a component for a slider, but it seems to be malfunctioning. Upon the initial rendering, I encountered the error: 'cannot read property style of undefined...' When I logged x[slideIndex-1], initially it returns undefined ...

Is AngularJS causing issues with Foundation modals? Any solutions to this problem?

Wondering how to manage Foundation4 modals with AngularJS? I've noticed that when I navigate from a modal to a new view, the old modal disappears but the page stays darkened as if it's still there in the background. I tried adding a class attribu ...

Tips on optimizing your AngularJS application for search engine crawling

Currently in the process of creating a single-page application with Angular.js. My main concern is ensuring the crawlability of the application, as routing is managed through ng-view on the client side while the server only provides a basic header file. C ...

Obtain the rotational value in 3D CSS using JavaScript by extracting it from the matrix3d()

My element has been 3D transformed in the following way: .foo { transform: rotateX(-30deg) rotateY(35deg); } Now, I am looking to retrieve these values using JavaScript. Extracting the 3D matrix is simple: var matrix = $('.foo').css('tr ...

Displaying numerous Google charts within a Bootstrap carousel

A bootstrap carousel has been implemented to showcase our company's data. The carousel includes a bootstrap table, images, and two Google charts: a pie chart and a stacked bar chart. The issue arises when the active class is not maintained for the Go ...

Do I have to include reject() in the executor when using promises in express.js?

If we choose not to handle rejection, is it necessary to include the reject parameter in the promise executor? For example: new Promise((res) => { res(a); }) ...

A guide on incorporating Union Types in TypeScript

Currently utilizing typescript in a particular project where union types are necessary. However, encountering perplexing error messages that I am unsure how to resolve. Take into consideration the type definition below: type body = { [_: string]: | & ...