The AngularJS ngInit directive is executed three times, while ngClick is only executed once

Despite browsing through various resources on this topic, I have not found a satisfactory answer to my question. The problem lies in a function that retrieves data from my database - when I execute it using ngInit, the function runs three times, whereas on an ngClick event, it only runs once, which is the desired behavior.

I came across some discussions mentioning that the repetition of the function is due to Angular watchers keeping track of code changes. While the repeated execution does not bother me much, the real issue arises when I set a variable to true at the beginning of the function and then switch it to false upon getting the data. Unfortunately, the variable goes back to being false prematurely, causing the code to run again unnecessarily.

For example:

controller.getItem = function(){
    controller.loading = true;
    service.getSelectedItem($routeParams._id).then(function(response){
        if(response.data.state === 'success'){
            controller.myItem = response.data.item;
            controller.loading = false;
        }
    });

}

HTML:

<div id="item">

<button id="clickMe" ng-click="controller.getItem()">Get data</button>

    <div class="panel panel-new">

        <div class="panel-header">

            <div class="row">

                <div class="col-xs-12">
                    <h4>My Item - {{ controller.myItem._id }} 
                    <small>added on: {{ controller.myItem.dateAdded | date: 'dd MMM yyyy' }}</small></h4>
                </div>

            </div> 

        </div> 

    </div>

</div>

After running thrice, my loading screen disappears but the content remains undefined. It is only after the third iteration that the content actually gets populated.

In summary, while the function works perfectly with an ngClick, executing it with ngInit causes it to run three times, disrupting its intended functionality. I am uncertain about how to tackle this issue effectively.

Answer №1

I would appreciate if you could provide a bit more elaboration on this topic. It is advisable to utilize ngInit within a specific controller for optimal functionality. By implementing it in the designated controller, the code will execute smoothly based on the expected behavior.

Answer №2

After extensive debugging, the root cause of the issue has been identified. It turns out that the problem stemmed from the code snippet present in my index page:

<div ng-if="auth" id="ngView" class="ngView">
    <div ng-view>
    </div>
</div>

My initial assumption was that it was creating a view, executing the function, then repeating the process multiple times. This explained why everything appeared to be happening more than once.

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

Switch out feature within prototype attribute looping

I'm attempting to substitute all hyphens in attributes with underscores. <a href="/page" id="someId" data-country="north-america" data-state="north-dakota">North Dakota</a> This is the code snippet I am using: var el = document.getEleme ...

The Challenge of Refreshing Static Site Generation in NextJS Version 13

I've encountered a problem with updating data on a basic data page. The situation is simple: there's a page that shows category data and another page that allows editing of the same data. After making edits and returning to the list page, I expec ...

The textures in three.js material do not interact with lighting sources

I am curious about whether a textured geometry can be successfully lit in three.js. In my current scene, I have noticed that all materials receive lighting effectively when using spotLight and directionalLight, except for those that have a texture applied ...

Limit the number of characters allowed for input in Sweet Alert using Angular

Requirement : The input box must limit the user to a maximum of 20 characters. In my Angular project, I have integrated Sweet Alert for displaying messages. Upon clicking a button, a Sweet Alert with an input type set as password will pop up. I want to ...

Start by using jQuery to add an opening tag before content and then append a

Initially, I am well-versed with the .wrapAll() method and it does not serve my current requirement. The existing markup cannot be altered, and I need to encapsulate everything within an <li> tag. This is the objective I aim to achieve: $('n ...

Bidirectional data binding in AngularJS custom directive

I have recently started working with Angular.js and I am attempting to create a custom directive with a controller containing functions that is connected to another controller. I want the object in the main controller ($scope.MyObj) to update in sync wit ...

What is the best way to add randomness to the background colors of mapped elements?

I am looking for a way to randomly change the background color of each element However, when I try to implement it in the code below, the background color ends up being transparent: { modules.map((module, index) => ( <div className='carou ...

Angular.js animation for element movement

I'm currently struggling to create a simple move animation. I am aiming for a similar effect to the one shown in this example (taken from another SO question). So far, I have managed to achieve this using the .animation() method. This is essentiall ...

Combining data using D3's bar grouping feature

I'm currently exploring ways to group 2 bars together with some spacing between them using D3. Is there a method to achieve this within D3? I found inspiration from this example. var data = [4, 8, 15, 16, 23, 42]; var x = d3.scale.linear() .doma ...

Inject user-provided data into a randomly generated string

I'm currently working on developing a topic generator that dynamically incorporates user input. The idea is to allow users to enter a keyword, such as "Dog," and have that input inserted into a randomly generated sentence. For example: Top 5 Ways To T ...

Instructions on passing a PHP variable as a parameter to a JavaScript function when a button is clicked

In my implementation of codeigniter 3, I have a view page where the data from $row->poll_question is fetched from the database. The different values within this variable are displayed on the voting.php page. Next to this display, there is a button label ...

Is there a way to effectively combine @Model and @Emit in VueJs using Typescript?

I could really use some assistance with @Model and @Emit decorators. I'm attempting to alter the order on click within my component, and I referred to the documentation found here: https://github.com/kaorun343/vue-property-decorator. Below is the code ...

What could be causing Laravel to fail to show the blade template?

I've been learning about Laravel's websocket and following a tutorial on it. I tried to implement the code exactly as shown in the tutorial, but I'm running into some issues. Here is the code for the controller: class CommentController exte ...

Creating interactive buttons on the fly in Angular

In my Angular application, I am attempting to create a button dynamically that calls the deleteRow() function and passes a username parameter upon click. Despite successfully passing the username to the controller, the generated button ends up passing unde ...

Implement localization for Vue-Tables2 data table

Check out this table example from my project. I am working on a multilingual website and I want the vue-table elements to be translated based on the user's language preference. Only the table elements need to be translated, not the actual data inside ...

Issue with angular ui-router transition override/intercepted/disrupted/terminated

Encountering these errors: Error: transition superseded at $StateProvider.$get (http://localhost:1337/angular-ui-router/release/angular-ui-router.js:2903:42) Error: transition prevented Error: transition aborted Error: transition failed After researc ...

Using a double for loop in VUE3 without altering the property

I am working with a 'data' props object that looks like this: data = [ { "label":"gender", "options":[ {"text":"m","value":0}, {"text":"f&q ...

When the child div reaches a width of 2%, it overlaps with the rounded container, adding a unique touch to

I have a long rectangular container with rounded corners. Inside the container, there are 3 child divs. Here is an image demonstrating the setup: In the illustration above, the first child container (white) and the third one (red) also have rounded corn ...

Exploring ways to utilize Next.js (React) for formatting date and time with either Moment.js or alternate

When deciding on the best method for handling date formats in my next front-end app, should I use Moment.js or JavaScript functions? The data is sourced from the backend as the date type, and I want it to be displayed in a user-friendly format while consid ...

information that appears for various URLs upon being clicked

Hey, I have a question regarding some Javascript and jQuery code that I could use your help with: jQuery: $(document).ready(function () { $( '.website' ).popover( { 'trigger' : 'hover', ...