Utilizing ng-change to trigger function several times within ng-repeat loop for input elements

Currently, I am experiencing a problem that involves an ng-repeat containing an input with ng-change() inside a directive template. This input is double way bound to a parent object. When I enter text into the input box, everything functions as expected and the parent object updates accordingly. However, if I replace the parent object from the directive's controller, I encounter an issue.

The problem arises when the parent object is replaced and the view is updated with the new values. At this point, a function similar to ng-change() is manually triggered for some calculation purposes. Strangely, I have noticed that the same function gets called again (for reasons unknown). The ng-model of the input is undefined during these automatic calls, leading to the parent object eventually having an undefined value.

I am puzzled about why the ng-change event is triggered after the controller method calls. Could this be related to the child scopes created by ng-repeat?

To provide context, I have already used track by $index in my code and have bound models to parentObj.something.something[$index]. Any assistance on resolving this issue would be greatly appreciated...

In my code, I have defined a directive as follows:

 module.directive('myDirective', function () {
        return {
            scope: {
                target: '=',
              },
            controller: 'DemoController',
            templateUrl: 'app/demo/html/demo.html'
}
});

Main template snippet:

<li ng-repeat="l in group_Main.mains"
<li ng-repeat="target in l.description.Value track by $index"
<li ng-repeat="(key, groups) in target.group track by $index">
 <div layout="row" layout-wrap myDirective  target="group"></div>
</li>
</li>
</li>

app/demo/html/demo.html: Directive's template

<div class="table_FY_height" flex ng-repeat="m in months track by $index">
<input ng-change="changeIt(target.targets.years[1].values.data[$index], target, year,parent, $index)" ng-if="$index > currentMonth" ng-model="target.targets.years[1].values.data[$index]"/> 
</div>

Within the directive's controller:

module.controller('DemoController', function($scope, $rootScope){
    changeIt(-1,$scope.target,$scope.year,$scope.parent);
}

In the directive's controller, I attempt to make an API call to update the target data:

 http.get(url).then({
    function(APIResponse){
for(var i=0; i<12; i++){
    target.targets.years[1].values.data[i] = APIResponse.targets.years[1].values.data[i]
}}, function(error){
    //error handling here}
    }

This action triggers the directive to update the view with the new values fetched from the API response. The function is initially called once per directive with a first argument of -1. However, subsequent runs occur with 'undefined' as the first argument. With each run using 'undefined', the target.targets.years[1].values.data[$index] becomes undefined as well.

If anyone has insights or suggestions on what might be causing this unexpected behavior, I would greatly appreciate it. I've been trying to troubleshoot this issue for hours.

Answer №1

After thorough investigation, I delved into the problem and discovered that the culprit in my situation was a directive attached to an input tag. This directive was manipulating the model after it had been bound, mainly for rounding purposes. By removing this logic and instead sending pre-rounded values from the server, the issue disappeared completely. From this experience, I deduced that the second ng-change event was triggered due to the directive modifying the model again. For anyone encountering similar difficulties, it's important to search for any other modifications made to the model post initial binding.

I am posting this response as the solution based on my personal encounter with the issue.

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

Unanswered matters lingering in the public chat

Currently, the code does not produce any errors in the console. Although the initial message.reply line executes correctly, the bot fails to register when someone types 'accept' or 'deny'. I've spent a considerable amount of time t ...

Using addClass and removeClass functions in JQuery when selecting a radio button

I am facing an issue with my radio buttons being displayed as images. When a picture (radio button) is selected, I want the other pictures to become hidden. To achieve this, I plan to add a class to the checked picture and then add another class to the unc ...

Different ways to showcase a value from the CSS file on the console using console.log

In this guide, you can learn how to create a custom directive in Angular by following this tutorial: Custom Directive Tutorial. The directive should function as intended. Still, I want to see the color value set in the CSS file displayed on the console us ...

Can you provide a brief explanation for this bubble sort JavaScript code?

Can someone please explain to me what the line j<len-i is doing in this bubble sort code? I believe removing -i from that line will still make the program work properly, var arr=[3,5,4,7,8,9,30,0,-1]; function bubble_Sort(arr){ var len = arr.length, ...

GraphQL failing to communicate with WP API

Any help is appreciated! I am currently retrieving data from a WP Rest API. When I run the WordPress site locally on my machine using http://localhost:8000 and access the graphql playground at http://localhost:3000/api/graphql, everything works fine as ex ...

Ensuring Vue.js correctly re-renders an array item

In my vue.js 2 project, I am working with an array that has the following structure: data() { return { ports: [ { id: 1, name: "example", "age": 10, scores: [ {index: 1, value: 100}, {index: 2, value: 200} ]}, { id: 2, ...

What is the best way to update HTML content using JSF reRender or Ajax load, and then rebind the updated DOM with AngularJS?

Let's analyze the following piece of code: <div id="dest"> <p>Original Content</p> <p>Some data</p> <ul> <li ng-repeat="i in items">{{i.name}}</li> </ul> </div> Alternatively, u ...

Can you explain the distinction between these two concepts in JavaScript?

I've come across an issue while assigning PHP values to JavaScript. var a = <?php echo 39; ?> JavaScript is throwing an error that says "Uncaught SyntaxError: Unexpected token ILLEGAL". However, when I assign PHP values in a slightly different ...

Is it possible for ajax to provide me with the information regarding the data size of the URL

Is there a way for the xjr object to access the total data size in KB or MB? I have been using the progress event and it can track this, so I was curious about obtaining the total data size. Here is the code snippet: var container = Pub.el('#super-1 ...

React Navigation ran into an issue with the specified location

It seems that I am encountering an issue where it is displaying a message stating "no routes matched for location '/'". However, the Header file clearly shows that there is a home component defined for this URL. https://i.sstatic.net/26516LfM.jpg ...

Struggle with registering fonts in Canvas using JavaScript

I've been struggling to add a custom font to my canvas for hosting the bot. Even though I'm not encountering any errors, the font fails to display on the host. Below is the code snippet: const { AttachmentBuilder } = require('discord.js&apos ...

Tips for transferring data from the Item of a repeater to a JavaScript file through a Button click event for use in Ajax operations

I am working with a repeater that displays data from my repository: <div class="container" id="TourDetail"> <asp:Repeater ID="RptTourDetail" runat="server" DataSourceID="ODSTTitle" ItemType="Tour" EnableViewState="false" OnItemDataBound="Rp ...

Issue with Angular-cli: typescript files not being generated when using the --dev option

Currently using angular-cli version 1.0.0-beta.14 with node version 6.6.0 on a Windows 32 bit x64 operating system. This setup utilizes the webpack version of angular-cli and I can successfully use ng build to compile. The output of ng build indicates that ...

Using selected option from dropdown as a value for a hyperlink

I'm attempting to transfer the chosen value from a dropdown menu to my link. This way, when I click on the specific link, it should trigger the corresponding action based on the ID selected from the dropdown. The alert shows the value, but now I need ...

Guide on sending the unique identifier of an element to the backend following a click event

Currently, I am working on a specific page in my project that lists movies. When you click on a movie, it directs you to a page where you can view all the information about that particular movie. I am utilizing SQL in my database and one of my ideas is to ...

Extracting Data from MongoDB and Presenting it Using AngularJS

Hey there! I'm currently diving into the MEAN stack and feeling a bit stuck. I've set up a project with Node.js, Express, Angular, and MongoDB. To interact with MongoDB, I used npm install mongodb Any guidance on how to pass data from MongoDB ...

Pressing the reset button on the search box triggers a JQuery and HTML function

I am new to this, so bear with me. I've simplified my styling for easy pasting here, but the concepts still apply. I have a list of items, a working search field, and functioning filter buttons. What I want is for the filter buttons to reset to &apos ...

What are the requirements for Web API to connect with models?

When using Angular, I am able to successfully send an HTTP request: $scope.addFiles = function (files) { for (var i = 0; i < files.length; i++) { var file = files[i]; $http.post('/api/files/addFiles', JSON.stri ...

Uploading images to an S3 bucket in base64 format using Angular 7

Within my Ionic 4 Angular 7 application, I am attempting to upload an image captured using the Cordova camera plugin. The output data from this Camera plugin is in the form of base64 image data. this.camera.getPicture(options).then((imageData) => { ...

Grails: the choice between a unified application or separate back-end and front-end apps

We are beginners in the world of Grails and have some concerns that we want to address: Issues related to scalability Utilizing the same back-end for multiple applications Do you think it's a good idea to stick with just one Grails application, ...