What is the best way to implement an ng-change function on multiple fields within the same page without causing a cyclic call loop?

In my page, I have three angular-moment-datepicker fields - a date picker field, a month picker field, and a year picker field respectively. Here is the code:

<input class="form-control" placeholder="BY DAY" ng-model="date" moment-picker="gDate" start-view="month" format="MM/DD/YYYY" today="true" ng-model-options="{ updateOn: 'blur' }" change="getData('day')" />
<input class="form-control" placeholder="BY MONTH" ng-model="month" moment-picker="gMonth" format="MM/YYYY" ng-model-options="{ updateOn: 'blur' }" change="getData('month')" />
<input class="form-control" placeholder="BY YEAR" ng-model="year" moment-picker="gYear" format="YYYY" ng-model-options="{ updateOn: 'blur' }" change="getData('year')" />

And here is the corresponding Angular function:

        $scope.getData = function(Level) {
            //Function logic here
        }

When selecting a date, I want to clear the month and year fields. However, this process triggers the ng-change event simultaneously for 'month' and 'year', leading to unexpected behavior and not displaying the selected value in the text field.

I tried using the following alternative function within the text fields:

$scope.checkForDateType = function() {
    //Logic to check date type
}

Unfortunately, the issue persists despite trying this approach. Any assistance on resolving this problem would be greatly appreciated.

Answer №1

I have discovered the solution. To solve the issue, a global variable needs to be set and defined with the data type. This variable should then be checked in all sections of the function.

$scope.setGlobal = function (from) {
    $scope.globelDateType = from;
}

$scope.getData = function (Level) {
    var dateRange = "";
    if ($scope.globelDateType == "") {
        $scope.setGlobal(Level);   // implementing new change
    } else {
        return false;
    }
    if (Level == 'day') {
       if ($scope.date != "") {
           var Value = $scope.date;
            var localTime = moment.utc(Value).toDate();
            localTime = moment(localTime).format('YYYY-MM-DD HH:mm:ss');
            dateRange = new Date(localTime);
       }else {
           $scope.setGlobal("");  // implementing new change
           return false;
       }
        $scope.month = "";
        $scope.year = "";
    } else if (Level == 'month') {
        if ($scope.month == "") {
           $scope.setGlobal(""); // implementing new change
           return false;
        }
        var Value = $scope.month;
        var localTime = moment.utc(Value).toDate();
        localTime = moment(localTime).format('YYYY-MM-DD HH:mm:ss');
        dateRange = new Date(localTime);
        $scope.date = "";
        $scope.year = "";
     } else {
        if ($scope.year == "") {
           $scope.setGlobal("");    // implementing new change
           return false;
        }
        var Value = $scope.year;
        var localTime = moment.utc(Value).toDate();
        localTime = moment(localTime).format('YYYY-MM-DD HH:mm:ss');
        dateRange = new Date(localTime);
        $scope.date = "";
        $scope.month = "";
     }
     if (dateRange != "" || dateRange != undefined) {
         searchService.getDataFromDb(Level, dateRange).then(function (result) {
            //process result
            })
     }

     $scope.setGlobal(""); // implementing new change
}

If any callback functions are needed, the setting of the global variable should only occur through the $scope.setGlobal() function. The value of this global variable along with the ng-model determines which loop to execute and triggers corresponding actions, while causing all other methods to return a false condition.

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

Best event for Angular directive to bind on image onload

I'm currently working on incorporating this particular jQuery plugin into my Ionic application. Although I have a good grasp of creating an Angular directive to encapsulate the plugin, I am encountering difficulties in successfully implementing it. B ...

Refresh a webpage using JavaScript (inside a jquery ajax call)

Seeking guidance on how to reload a page using JavaScript, I have created the following function: function update(id, name) { if(/^\d+$/.test(id)) { $.ajax({ url: baseurl + "/url/action/param/" + id + "/param2/" + unescap ...

Making a chain of multiple AJAX requests using jQuery

My current challenge involves retrieving data from select options on a website using JavaScript. Specifically, I am trying to obtain a list of zones within my country from a website that has this information. The issue I am facing is the hierarchical disp ...

Display a complete calendar with the date picker on a webpage

Currently experimenting with React to build a straightforward application. Admiring the appearance of full calendars from these date pickers (once clicked): Material-UI React-Toolbox Wondering if it's feasible to present the full calendar directly ...

What is the best way to use a computed property as a style value for a component in Vue.js?

My component's template includes the following HTML element: .grid-item(:style="{ width: columnWidth, backgroundColor: 'blue' }") I want to dynamically set the width of this element using a computed property: computed: { columnWidth () ...

As my character slides off the moving platform in this exciting Javascript canvas game, my heart

Can anyone help me figure out how to keep my player on the moving platform? I'm not sure if I need to add gravity or something else. I'm still learning the ropes. export function checkTopCollision({ item1, item2 }) { return ( item1.y + item ...

angularjs controller scope initialization through a service

To maintain scope data between route changes, I developed a service that retrieves saved data for a controller to use on scope initialization. app.factory('answerService', function () { var answers = { 1 : { text : "first answer" }, ...

Issue with Vue 2: Promise does not resolve after redirecting to another page

Although I realize this question might seem like a repetition, I have been tirelessly seeking a solution without success. The issue I am facing involves a method that resolves a promise only after the window has fully loaded. Subsequently, in my mounted h ...

The error message "TypeError: undefined is not an object (evaluating '_reactNative.Stylesheet.create')" occurred in a React Native environment

I've been working on a project in React Native and have successfully installed all the necessary dependencies. However, upon running the code, I encounter the following error message: TypeError: undefined is not an object (evaluating '_reactNativ ...

The ng-click function does not function properly when used within a script

I started using angular-bootstrap in my AngularJS project to incorporate dialogs. This is the code snippet I have in my HTML: <script type="text/ng-template" id="create.html"> <div class="modal-header"> <h3 class="modal-title">Welcom ...

href not functioning properly on subsequent clicks, whereas onclick remains active

I'm experiencing an issue with a button that opens a modal. When clicking the button, it's supposed to open a new page in the modal and also make an API call for processing before loading the new page. <a class="btn btn-primary" type='b ...

Preventing users from navigating away from the page without choosing an answer in a React application

My dilemma involves the implementation of a question component, where I aim to prevent users from leaving a page without selecting an answer. Below is my question component: import React, { Component } from 'react'; import { Link } from 're ...

The onload function on the iframe is triggering twice in Internet Explorer 11

I am encountering a strange issue with an iframe in HTML that has an onload function. When using IE11, the onload function is being triggered twice, whereas it works fine in Chrome. Here is the HTML code: <iframe src="someurl" onload="someFunction( ...

Executing a function on page load instead of waiting for user clicks

I've been researching a problem with onclick triggers that are actually triggered during page/window load, but I haven't been able to find a solution yet. What I need is the ID of the latest clicked button, so I tried this: var lastButtonId = ...

javascript send variable as a style parameter

screen_w = window.innerWidth; screen_h = window.innerHeight; I am trying to retrieve the dimensions of the window and store them in variables. Is there a way to then use these variables in my CSS styles? For example: img { width: screen_w; height: s ...

Enhance the Error class in Typescript

I have been attempting to create a custom error using my "CustomError" class to be displayed in the console instead of the generic "Error", without any success: class CustomError extends Error { constructor(message: string) { super(`Lorem "${me ...

New and personalized bindings in knockout.js for dynamically updating a dropdown menu based on the selection in another dropdown menu

I have been using knockout for a few months now and have been getting along just fine. However, I recently encountered an issue where I cannot update the options within a SELECT tag because the ajax methods that retrieve data from the server are inside a ...

Tips on incorporating an item into an array solely when a specific condition is met

Consider the following arrow function that creates an array: const myFunction = () => ["a", "b", "c"]; I am looking to modify this function to add another element if a specific argument is true. For example, I want it to look like this: const myFunc ...

What is the best way to retrieve data from divs that are nested within another element using Javascript?

I am currently working on implementing a modal that will showcase specific information based on the event-card it originates from. Here is an HTML snippet showcasing an example event-card: <div class="event-card upcoming hackathon"> <d ...

Angular not firing slide.bs.carousel or slid.bs.carousel event for Bootstrap carousel

I've searched high and low with no success. I'm attempting to detect when the carousel transitions to a new slide, whether it's automatically or by user click. Despite my numerous attempts, I have been unable to make this event trigger. I ha ...