Why is ng-change not functioning properly, especially in conjunction with the Select element?

HTML

<select ng-model="selectedName" ng-change="retrieveSelectedClass()" ng-options="(item.name||item) group by item.groupName for item in names"
            class="code-helper" id="code-helperId">
        <option value="">Select Option</option>
</select>

JavaScript

var globalEditor1 = null;
var globalMergeEditor = null;
var widgets = [];
var timeout;
var app = angular.module('myApp', []);
var previousValue;

app.controller('OrderFormController', function($scope, $http) {

    $scope.retrieveSelectedClass = function() {
        $scope.isPaneShown = true;
        if ($scope.selectedName === undefined) {
            $scope.isPaneShown = false;
            return;
        }
        if ($scope.selectedName.groupName === 'Create New') {
            if (globalEditor1) {
                if (!globalEditor1.isClean()) {
                    var r = confirm("You have unsaved changes, are you sure you want to proceed ?");
                    if (r != true) {
                        $('.code-helper').val(previousValue);
                        $scope.isPaneShown = false;
                        return;
                    }
                }
            }
            $scope.isPaneShown = false;

        } else {
            if (globalEditor1) {
                if (!globalEditor1.isClean()) {
                    var r = confirm("You have unsaved changes, are you sure you want to proceed ?");
                    if (r != true) {
                        $('.code-helper').val(previousValue);
                        $scope.isPaneShown = false;
                        return;
                    }
                }
            }

        }
    }

});

$(document).ready(function() {
    $('.code-helper').select2({
        placeholder: 'Select a command to begin'
    });
    $('.code-he pd crlper').on('select2:selecting', function(evt) {
        console.log($('.code-helper').val());
        previousValue = $('.code-helper').val();

    });
});

I am having an issue with the ng-model and ng-change interactions. Despite being attached, sometimes the ng-change function does not get triggered under specific circumstances.

When the condition !globalEditor1.isClean() = true is met, I attempt to replace the selected value with the previous value. This process works correctly. However, when trying to change the value from the select tag afterwards, the ng-change event fails to fire.

jsfiddle

Take a look at the jsfiddle here

To reproduce the issue:

Follow these steps after running the provided link: 1) Choose "AccountProcessorTest" from the dropdown menu 2) Confirm the alert dialog 3) Select "AddPrimaryContact" and cancel the alert prompt 4) Notice that the previous value is retained 5) Try selecting "AddPrimaryContact" again

The ng-change event will not be triggered.

Answer №1

Here is a functioning piece of code:

ng-change="updateSelectedClass(selectedItem, '{{selectedItem}}')"

JavaScript

$scope.updateSelectedClass = function(newVal, oldVal) {
    var oldValSelection = {};
    if (angular.isUndefined(oldValSelection.id) && oldVal.indexOf('"id"') !== -1) {
        oldValSelection = JSON.parse(oldVal);
    }
    var possibleOldSelections = $filter('filter')($scope.selections, {
        id: oldValSelection.id
    }, true);
    oldVal = possibleOldSelections[0];

}

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

Tips for looping through multiple states within a single table

I need help with combining data from two different states, campaigns and stats, into a single table. The campaigns state includes sr no, campaign id, campaign name, and campaign status, while the stats state includes reach, sent, delivered, views, clicks ...

What is the reason IE7 does not recognize these two strings as equal?

My event handler is designed to remove an element from a list if the corresponding checkbox is unchecked. When the checkbox is clicked, I first capture the value of the label associated with it: var label = $(this).next().html(); Next, I loop through the ...

Ways to invoke a function in Angular2 when the Boolean condition is met

Within my component class, I have implemented a popup function along with a Boolean flag that returns true or false based on specified conditions. In the template class, I want the popup function to be triggered when the flag becomes true, displaying a pop ...

Updating data scope in AngularJS using $http request not functioning properly

I am facing an issue where the $scope.user_free_status is not updating when I set a user free, but works perfectly fine when I unset the parameter. It's strange that I need to reload the page in one case and not the other. The data fetched is stored i ...

Incorporating a basic search feature into Ajax

At the moment, only results appear when you modify the query. I want to modify this to allow user input. I have set up the fields, but I need help adjusting my ajax code to accept the new search criteria which is crucial for functionality. This is what m ...

The React.js search feature consistently retrieves identical content every time

I am currently working on a project to create a search engine using React.js, specifically to search for GIPHY gifs through their API. However, I have encountered an issue where the gifs displayed do not update when I type in new words after erasing the pr ...

Accessing information via a PHP script with the help of AJAX and jQuery

In the process of developing a gallery feature that displays a full image in a tooltip when hovering over thumbnails, I encountered an issue where the full images extended beyond the viewfinder. To address this, I decided to adjust the tooltip position bas ...

In the strict mode tree, a reference named "grid" has been discovered

I encountered the following warning in the console: Warning: A string ref, "grid", has been found within a strict mode tree. String refs can potentially lead to bugs and should be avoided. It is recommended to use useRef() or createRef() instead. T ...

Unusual marking on the navigation bar

Currently, I am making updates to a website that was created by a previous employee long before I joined the team. One of the requested changes is to eliminate the orange box surrounding the navigation links. The navigation appears to be generated using Ja ...

Encountering a Problem: [$injector:modulerr] Inability to Create App Module in AngularJS + Karma + Jasmine Setup

We are currently working on a large project that involves multiple controllers, factories, configs, and more. Recently, I decided to integrate karma+ jasmine for writing unit test cases. However, I am encountering the error mentioned above. Despite trying ...

What is the best method for importing Bootstrap into SvelteKit?

I am currently working on a SvelteKit website. I have integrated Bootstrap 5 into my project by adding it to the app.html file provided by the SvelteKit Skeleton starter project: <!-- Bootstrap styles and javascript --> <link rel="stylesheet ...

Increasing the upward motion of the matrix raining HTML canvas animation

Recently, I've been experimenting with the Matrix raining canvas animation here and I was intrigued by the idea of making it rain upwards instead of downwards. However, my attempts to achieve this using the rotate() method resulted in skewing and stre ...

Steps to establish a connection with a remote MYSQL database using the actual IP address in Node.js

In my Nodejs file, I have set up the connection as follows. The issue arises when attempting to connect to the remote database on a server. module.exports = { host: '234.32432.32432',//this is an example IP address and not a real one. use ...

Incorporate a map (using leafletjs or Google Maps) as a subtle backdrop

I am currently working on a one-page website and I would like to include a map as a background behind the "contact" section. The map can be set to float, draggable, or positioned at the back. I have experience using both the Google Maps API and LeafletJS, ...

Regular expressions won't produce a match if the string is empty

At present, I am employing the regular expression /^[a-zA-Z.+-. ']+$/ to ascertain the validity of incoming strings. If the incoming string is devoid of content or solely comprises whitespace characters, my objective is for the code to generate an er ...

The element type 'HTMLElement' does not contain a property named 'pseudoStyle'

Currently experimenting with adjusting the height of a pseudo element using Typescript. An error is popping up in my IDE (vscode) as I go along. This is the code snippet I am working with. // choose element let el: HTMLElement = document.getElementById( ...

The ES6 method of binding click handlers with parameters in React

After reading numerous articles on the usage of () => {} syntax, binding in the constructor, and binding in the props, I have come to understand that binding this can be performance-intensive. Furthermore, automatic binding with arrow functions incurs a ...

Deselecting a radio button using AngularJS

I currently have three radio buttons like this: <input type="radio" name="project" data-ng-model="vm.defaultProject" data-ng-value="projectUserConnection.project" /> If I select one of the radio buttons, I am unable to deselect it unless I select a ...

When attempting to use a jQuery-formatted JSON object within an <optgroup > returned via AJAX from PHP and MySQL, it appears to be incompatible with Select2

After spending an entire day attempting to create a PHP script that converts MySQL Query results into a JSON object for <optgroup> in Select2, I finally found a solution. However, when I implemented it, nothing appeared in the Select2 dropdown menu. ...

Automatically Populate Text Field with the URL of the Current Page

I am hoping to automatically fill a hidden text field with the URL of the current page so that I can keep track of where form submissions are coming from. This simple solution will help me streamline my inquiry responses and save time. To clarify, upon lo ...