Angular: Issue with Controller Constructor Function Executing Repeatedly

My concern lies in the fact that the Controller constructor seems to be executing multiple times. It appears that if I have 2 Directives associated with a specific Controller, it runs 2 + 1 times, and for 3 Directives, it runs 3 + 1 times...and so on. This issue becomes even more problematic when there is an ajax request within the controller fetching data unnecessarily...

What could be causing this behavior? I worry about the excessive ajax requests being made...

HTML:

 <span ng-controller="MenuController as MenuCtrl">
    <main-menu></main-menu>
 </span>

Controller:

  var howManyTimes = 0;
  angular.module("shredkit", ["myDirectives"])

  .controller("MenuController", function(){
    ++howManyTimes;
    console.log("HOW MANY TIMES? THAT MANY: " + howManyTimes )
  })

Directive:

angular.module("myDirectives", [])

  .directive("mainMenu", function(){
    return{
      restrict:"E", // type of directive - 'E' - element
      templateUrl:'templates/main-menu.html',
      controller:"MenuController",
      controllerAs: "MenuCtrl"
    };
  })

Answer №1

Each instance of the ng-controller tag will trigger your controller to execute:

<span ng-controller="MenuController as MenuCtrl">

Furthermore, every time a new DOM element is created with this scope under its control:

controller:"MenuController"

This behavior is due to controllers in Angular not being singletons - they are built and initialized each time they are used.

If you need to use multiple controllers to share data, consider one of the following two approaches:

  1. Have a parent controller that wraps all child controllers.
  2. Utilize a shared service to store and manage state.

Answer №2

Utilizing the MenuController both within a div and a directive can lead to redundancy as controllers are triggered for each assigned element, including those designated within directives.

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

PHP encountering a bad escaped character while parsing JSON using JSON.parse

I'm encountering an issue with JSON parsing. In my PHP code, I have the following: json_encode(getTeams(),JSON_HEX_APOS); This returns a large amount of data. Sample data: To provide more clarity, let's assume I have this: my_encoded_data ...

Fill every empty element with elements from another array

I'm struggling to grasp the concept of arrays. I have two arrays and I want to replace the null elements in one with the elements from the other. Here is what I have currently: var arr1 = [1,2,3,4] var arr2 = [null, 99, null, null] arr2.map((item) = ...

What are the reasons behind the asynchronous behavior of Angular translate in version +2?

I have been using angular translate version 1.x for a while now and I find the $translate service quite easy to use. When working with this version, you can simply do the following in a controller: $scope.whatever = $translate('WHATEVER'); How ...

Create a dynamic calendar by integrating dates with Javascript and an HTML table

Recently, I decided to delve into web design again and embark on a challenging project for my father's baseball business. The main task at hand is creating a detailed calendar using HTML tables. After spending a considerable amount of time perfecting ...

How to use Javascript to pause an HTML5 video when closed

I am new to coding and currently working on a project in Adobe Edge Animate. I have managed to create a return button that allows users to close out of a video and go back to the main menu. However, I am facing an issue where the video audio continues to p ...

Creating a consolidated System.config mapping for @angular modules using a single .js file

Currently in the process of developing an Angular 2 application, with the specific requirement to consolidate all resulting Javascript files into a single .js file called output.js. Now, the challenge is to incorporate map configuration within System.conf ...

Displaying a component after retrieving a value from AsyncStorage in a React Native application

I have developed a React Component that saves user settings in the AsyncStorage and retrieves them upon loading. The functionality of storing and retrieving data is working fine, but I am facing an issue where the component renders before the values are ...

Utilize Axios in Vue.js to fetch and process data from a REST API endpoint in C#

After successfully creating and deploying an API on Azure, I am trying to display the response in an alert box using javascript (Vue.js). The test method of my API returns the string "working". You can test the API here. This is the code snippet from my A ...

JavaScript queries in Selenium WebDriver

Lately, I have been using the selenium webdriver (nodejs module) along with mocha for writing automation tests, and encountered a few challenges along the way. Issue with Scrolling driver.findElement() seems to return false as it is unable to find the e ...

The admin-ajax.php file in WordPress consistently fails to return any value other than

I developed a WordPress ajax plugin, but I am facing an issue where admin-ajax.php always returns 0 and the plugin doesn't work as expected. Here is the code I have implemented: add_action( 'wp_ajax_example_ajax_request', 'example_aja ...

Exploring JSON parsing capabilities in Next.js

As a newcomer to Javascript, I have a query that may seem silly. I am attempting to parse JSON in the main function of Nextjs. However, when I try to parse JSON in the main function before the return statement, I encounter the error SyntaxError: Unexpected ...

Hide other dropdown when one dropdown is clicked

I am currently working with a dropdown data-filter in combination with the isotope plugin. My goal is to have the ability to close an open dropdown when another list item is clicked, and also have the arrow twirl down when the dropdown is open. I am seek ...

Trouble arises when attempting to establish an isolated scope within Angular alongside UI Bootstrap

My table of data is set up with AngularJS, and one of the columns is calculated using a function in the controller. On my webpage, I have a button that opens a modal. When I use UI Bootstrap to open the modal, it creates a new isolated scope (child of the ...

I'm trying to create a drop-down list in JS that will save selected options to a database using PHP. I'm feeling a bit lost, anyone

My goal is to upload a pdf file with specific options that determine its category. The challenge arises when creating multiple options, as the second option depends on the first choice and involves JavaScript functionality for which I am unsure how to stor ...

Could anyone explain why this basic angularjs jsfiddle isn't functioning properly?

Could someone explain why this basic angularjs jsfiddle isn't functioning? var myApp = angular.module('myApp',[]); myApp.controller('MyCtrl', ['$scope', function MyCtrl($scope) { $scope.name = 'Superhero'; ...

What benefits does minifying server-side nodejs code provide?

Is there a benefit to minifying Node.js code in the same way as minifying JavaScript, particularly for reducing size and improving network download speed? When a file is required in Node.js, it is loaded into V8 and processed and stored in memory in some f ...

Scrolling vertically using window.open functionality

I am trying to open a pop-up window using window.open. I would like the scrollbars to appear only if necessary. Unfortunately, in Safari, the scrollbars do not show up unless I include scrollbars=1 in the code. However, this also causes horizontal scrollb ...

Displaying a notification for a multi-selection using JavaScript

I need help with a piece of Html code I have. It's a list of countries, and what I want is to show an alert when one or more countries are selected to display which ones were chosen. I'm working with JavaScript only and don't want to use Jqu ...

How can I display color without using Winston's color formatter in text?

Currently, I am in the process of developing a logging module using winston as the selected logging framework. It offers the convenience of specifying colors, which is particularly appealing when utilizing the Console transport. However, if I were to defin ...

Implement a Selection Feature in Angular

Currently, I am working on an application where users can add new rows with the same fields. One of the requirements is to allow users to add an option to a select element. While I have successfully implemented this in jQuery, I am facing challenges integr ...