Adding ngChange programmatically in Angular without using attributes is a common challenge faced

I am attempting to replicate the functionality of the ng-change attribute within a directive without making changes to the HTML (thus excluding the use of the ng-change property).

After examining the Angular source code for the ngChange directive, I have created a directive that functions as follows: (Essentially, this directive involves calling the blur() method on a select field when the model is altered)

.directive('blurOnChangeFix', ['$timeout',
    function($timeout) {
        return {
            restrict: 'AEC',
            require: 'ngModel',
            link: function($scope, element, attr, ngModel) {
                    // automatically blur element on ngModel change
                    ngModel.$viewChangeListeners.push(function() {
                    $timeout(function() { // IE bug fix
                        $(element).blur();
                    }, 100);
                });
            }
        };
    }
]);

Implementing it as follows:

<select
    id="test"
    ng-options="option for option in ['test1', 'test2'] track by option"
    class="form-control"
    ng-model="form.test"
    ng-required="true"
    blur-on-change-fix
></select>

However, is this the optimal solution? Are there alternative methods to achieve the same result? What about using scope.change()?

Thank you

Answer №1

It seems like you are looking to add a $watch function to your model. Here is an example:

link: function($scope, element, attr, ngModel) {
    $scope.$watch(attr.ngModel,function(newVal,oldVal) {
        element.blur();
    })

You mentioned wanting to take action when the model changes, which is exactly what the $watch function allows you to do.

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

Reasons Behind the News Not Being Retrieved Using [XML JS Query]

Can you help me troubleshoot my code? <!DOCTYPE html> <html> <head> <meta charset="utf-8"> <meta name="viewport" content="width=device-width"> <title>News Site</title> <script> window.document.onload = ...

Generating input fields dynamically in a list and extracting text from them: A step-by-step guide

I am designing a form for users to input multiple locations. While I have found a way to add input boxes dynamically, I suspect it may not be the most efficient method. As I am new to this, I want to ensure I am doing things correctly. Here is how I curren ...

Forge: Securely encrypting massive files

I rely on the forge framework for implementing PGP functionality, specifically for encrypting large files (2gb or larger) while minimizing RAM usage. What would be the most efficient approach to achieve this? ...

Having difficulty personalizing the email template on AWS SES

I am currently working on setting up a forgot password email system using AWS SES. Below is the template I have created: { "Template":{ "TemplateName": "forgotpasswrd", "SubjectPart": "Forgot ...

JQuery class for swapping elements upon scrolling

I am currently working on a navigation bar that changes classes to create a fading effect for the background. The approach I have taken involves targeting the window itself and monitoring the scroll position of the user. If the user scrolls down more than ...

NPM encountered difficulties in resolving the dependency tree

I seem to be encountering a persistent issue that I cannot resolve on my own. My attempt to update webpack and webpack-cli in a project has been met with repeated errors of this nature: npm install webpack@latest --save-dev npm ERR! code ERESOLVE npm E ...

Change the type of an object to a different type

Within my class, I have set the type of range to IntervalRange. export class Test {range: IntervalRange;} Then, in the parent class, I initialize the value: export class TestInitializer { Create(){ return <Test>{ range: IntervalRange.i ...

A Step-by-Step Guide to Setting Up a Scoreboard for Your Rock Paper Scissors Game

I'm new to JavaScript and I want to create a rock, paper, scissors game from scratch. My Game Plan: Once the user clicks on an option (rock, paper, scissors), the game will display their score and the computer's score along with the result of t ...

tips for dynamically highlighting search bar after choosing a different dropdown option - vuejs

I need to filter products in my application based on name and category. To achieve this, I have included a search text box and a dropdown select box. The dropdown select box offers two options: 1. Search products by name 2. Search products by category name ...

Which specific event(s) are triggered when transitioning to a sticky state in ui.router?

I've been working on an AngularJS app that utilizes ui.router along with the ui.router-extras plugin, specifically the sticky-state module. This module allows me to cache the rendered DOM starting from a specified parent state. The issue I'm fac ...

Troubleshooting issue with ng-selected functionality in Angular version 1.5.7

I am facing an issue with a select element in Angular 1.3.9 where the default selected data is set using ng-selected. However, after upgrading to Angular 1.5.7, the ng-selected functionality stops working and the default date is not being set. How can we ...

Allow the response to be returned in the parent function by using the $.post method

I have a question regarding this particular code snippet: null. Why is the server_request function not returning the responseText as expected? And how can I modify it to achieve the desired outcome?</p> ...

Will there ever be a possibility in the future to compile from D 2.0 to Javascript?

An experienced C++ programmer (that's me) is venturing into other programming languages and considering the value of learning more about D 2.0. The clean, fresh rewrite of D has caught my eye with its pragmatic and wise choices. Now, I'm eager to ...

An exploration of effortlessly moving elements using webdriver.io - the power of

I have been attempting to utilize the drag and drop method in WebDriver.io, but I am encountering issues. I followed the example for drag & drop on this website: https://www.w3schools.com/html/html5_draganddrop.asp. This functionality is essential for ...

Every time I switch views using the router in vue.js, my three.js canvas gets replicated

After creating a Vue.js integrated with three.js application, I encountered an issue with the canvas getting duplicated every time I opened the view containing the three.js application. The canvas remained visible below the new view, as shown in this image ...

Retain the chosen values even after submitting the form

Consider the following form: <form method="get" action=""> <select name="name"> <option value="a">a</option> <option value="b">b</option> </select> <select name="location"> <opt ...

typescript loop with a callback function executed at the conclusion

I am struggling with this code and it's driving me crazy. addUpSpecificDaysOfWeek(daysInMonth: any, callbackFunction: any){ var data = []; var that = this; daysMonth.forEach(function(day){ that.statsService.fetchData(that.userid, d ...

During the build process, the parameters in Next.js are not accessible

I am currently using Next.js 13 with the experimental app directory. My application utilizes dynamic routing in the following format: https://app.domain/[itemid]/[slug] Within my [slug] directory, if I create a server-side route file pages.jsx with th ...

What is the best way to insert an iframe using getElementById?

I am looking to make some changes in the JavaScript code below by removing the image logo.png lines and replacing them with iframe code. currentRoomId = document.getElementById('roomID').value; if ( document.getElementById('room_' + c ...

Acquire information using Vue through HTTP requests based on Router parameters

I have been searching for a solution to this issue and even referred to the example provided on the Vue Router documentation, but I am still encountering difficulties. My goal is to make an HTTP call when a component loads initially, then monitor the route ...