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

Analyzing JSON data and creating a tailor-made array

My Dilemma { "rowId": "1", "product_name": [ "Item A", "Item B", "Item C", "Item D", "Item E" ], "product_tag": [ "123456", "234567", "345678", "456789", "5678 ...

The installation of npm modules is failing with the error message: "'react-scripts' is not recognized as a valid command, internally or externally."

As I revisited my old project on GitHub, things were running smoothly a few months prior. However, upon attempting to npm install, I noticed the presence of the node modules folder and encountered some npm errors. https://i.stack.imgur.com/awvjt.png Sub ...

Changing the image's flex-grow property will take precedence over the flex settings of other child

This is the error code I am encountering, where "text1" seems to be overridden <!DOCTYPE html> <html lang="en"> <head> <meta charset="utf-8"> <!--mobile friendly--> <meta name="view ...

What is the process for importing something from index.js within the same directory?

My folder structure is similar to the one below /components/organisms -- ModuleA.vue -- ModuleB.vue -- index.js The content of index.js: export { default as ModuleA } from "./ModuleA.vue" export { default as ModuleB } from "./ModuleB.vue&qu ...

guide on incorporating Google Maps in a Vue.js application

Can anyone help me with displaying a Google Map using Vue.js? I have provided the code below, but I keep getting an error saying "maps is undefined" even though I have installed all the necessary dependencies for Google Maps. <div id="map"></div& ...

Deciphering the '$' symbol in the Cheerio API

I'm feeling a bit confused about the significance of using the $ sign in the Node.js Cheerio API. Take for instance the snippet of code below: if(!error){ var $ = cheerio.load(html); var title, release, rating; var json = { title : "", ...

Removing cookies after sending a beacon during the window unload event in Chrome

Here's the situation: I need to make sure that when the browser is closed or the tab is closed, the following steps are taken: Send a reliable post request to my server every time. After sending the request, delete the cookies using my synchronous fu ...

Do not ask for confirmation when reloading the page with onbeforeunload

I am setting up an event listener for the onbeforeunload attribute to show a confirmation message when a user attempts to exit the page. The issue is that I do not want this confirmation message to appear when the user tries to refresh the page. Is there ...

Which one should you begin with: AngularJS or Angular 2?

Interested in learning Angular and curious about the differences between Angular, AngularJS, and Angular 2. Should I focus on educating myself on Angular or go straight to Angular 2, considering it's now in beta version? Is there a significant differ ...

Why is `screen` important?

Recent articles in June 2020 discussing "how to utilize react testing library" often showcase a setup similar to the one below: import React from 'react'; import { render, screen } from '@testing-library/react'; import App from '. ...

Getting variables from different functions in Python can be achieved by using the return

I am trying to implement a feature where I can fetch a search term from the function getRandomVideo() and then use it in a jQuery statement. For example, if I get "Beethoven" as the search term from the variable searches, I want to use it to retrieve JS ...

"Exploring the concept of odd and even numbers within the ng-repeat

Can anyone help me with detecting odd or even numbers in an ng-repeat? I have created a fiddle that displays some dots randomly showing and hiding. Now, I want to change the background color so that odd numbers are green and even numbers are red. function ...

Disable the click event using jQuery

$("button").click(function (){ $("<button>Start</button>).appendTo('main'); }); The code above introduces a functionality where clicking a button generates another button dynamically. However, each subsequent click kee ...

Controlling hover effects with Material-UI in a programmatic way

I have integrated the following Material-UI component into my application: const handleSetActive = _spyOn => { linkEl.current.focus(); }; const linkEl = useRef(null); return ( <ListItem button component={SmoothScrollLink} t ...

Chrome does not support top.frames functionality

I have three HTML pages: main.html, page1.html, and page2.html. I am displaying page1.html and page2.html within main.html using the code below. <!DOCTYPE html> <html> <frameset frameborder="1" rows="50%, *"> <frame name="f ...

Handling OnClick events in D3 with Websocket Integration

My goal is to implement a Websocket in JavaScript that transmits a variable obtained when clicking on a node in a D3 chart. While I have made progress using static data, I'm struggling with initiating the code upon node click to retrieve the "user inf ...

Calculate sums in ReactJS without the need for a button

Adding a few numbers might seem like an easy task, but I've been unable to do so without using an explicit button. // Using useState to handle state changes const [ totalCount, setTotalCount ] = useState(0) // Function to add numbers of differ ...

I am seeking advice on how to incorporate JavaScript to adjust slider values and add numerical values or prices. Any suggestions would

Seeking assistance with a unique project: I am currently developing a calculator that allows users to utilize sliders to select the best option for themselves across various categories. My experience with JavaScript is limited, so I decided to reach out h ...

Executing a script within an ASP.NET MVC Project

Currently, I'm in the process of developing a project in MVC that requires using AJAX to fetch XML from an external source. However, I have encountered a challenge where I am unable to directly make the AJAX call due to a XMLHttpRequest same domain po ...

An error was encountered in the index.js file within the app directory when running the webpack

Recently, I was told to learn react.js even though my knowledge of javascript is limited. Nevertheless, I decided to dive in and start with a simple "Hello World" project. Initially, when I used the index.js file below and ran webpack -p, everything worke ...