Detecting changes in input elements when setting values in AngularJS

Access Code:

http://jsfiddle.net/mb98y/309/

HTML

<div ng-app="myDirective" ng-controller="x">
    <input id="angular" type="text" ng-model="data.test" my-directive>
</div>
    <button onclick="document.querySelector('#angular').value = 'testg';">click</button>

JavaScript

angular.module('myDirective', [])
    .directive('myDirective', function () {
    return {
        restrict: 'A',
        link: function (scope, element, attrs) {
            scope.$watch(attrs.ngModel, function (v) {
                //console.log('value changed, new value is: ' + v);
                alert('value change: ' + scope.data.test);
            });
        }
    };
});

function x($scope) {
    //$scope.test = 'value here';
    $scope.data = {
        test: 'value here'
    }
}

http://jsfiddle.net/mb98y/310/

HTML

<div ng-app="myDirective" ng-controller="x">
<input id="angular" type="text" my-directive="test">{{test}}</div>
<button onclick="document.querySelector('#angular').value =  'testg';">click</button>

JavaScript

angular.module('myDirective', [])
    .directive('myDirective', function () {
    return {
        restrict: 'A',
        scope: {
            myDirective: '='
        },
        link: function (scope, element, attrs) {
            // set the initial value of the textbox
            element.val(scope.myDirective);
            element.data('old-value', scope.myDirective);

            // detect outside changes and update our input
            scope.$watch('myDirective', function (val) {
                element.val(scope.myDirective);
            });

            // on blur, update the value in scope
            element.bind('propertychange keyup change paste', function (blurEvent) {
                if (element.data('old-value') != element.val()) {
                    console.log('value changed, new value is: ' + element.val());
                    scope.$apply(function () {
                        scope.myDirective = element.val();
                        element.data('old-value', element.val());
                    });
                }
            });
        }
    };
});

function x($scope) {
    $scope.test = 'value here';
}

I want to click a button to set the input element's value, which should be retrievable by AngularJS using ng-model or a scope object.

However, when changing the element's value with

document.querySelector('#angular').value =  'testg';
,

neither AngularJS $watch nor bind function can capture the value change event. If words are typed into the input element using the keyboard, both functionalities work.

How can I detect changes in the input element's value when setting it in this manner in AngularJS?

Answer №1

One way to handle data binding is by using two-way data binding, which helps avoid certain scenarios.

 <input ng-model='ctrl.field' />

 <button ng-click='ctrl.field = "new value"'>change</button>

Another option is to utilize the ng-change directive in conjunction with ng-model, allowing for actions to be taken when the model's value changes.

 <input ng-model='ctrl.field' ng-change='alert("changed!")' />

If there is still a need to modify values directly in the DOM outside of Angular, triggering events that Angular listens to, such as blur or keypress, can be employed.

 <button ng-click='$("#id").val(a); $("#id").trigger("blur")'>change</button>

Alternatively,

 <button ng-click='angular.element("#id").val(a); angular.element("#id").trigger("blur")'>change</button>

Answer №2

Check out the updated fiddle here.

Avoid using querySelector in Angular, similar to avoiding jQuery, unless absolutely necessary.

To update textbox contents automatically in Angular, simply modify $scope.data.test. Ensure that the button shares the same controller for scope sharing and use ng-click instead of onclick:

<div ng-app="myDirective" ng-controller="x">
    <input id="angular" type="text" ng-model="data.test" my-directive=""></input>
    <button ng-click="data.test = 'testg';">click</button>
</div>

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

Conceal the button briefly when clicked

How can I disable a button on click for a few seconds, show an image during that time, and then hide the image and display the button again? HTML: <input type="submit" value="Submit" onclick="validate();" name="myButton" id="myButton"> <img st ...

Use regular expressions and JavaScript to enclose a series of English letters within a wrapper

I am looking to enclose a series or cluster of consecutive English characters within a <span> tag. In simpler terms, I aim to alter the appearance of English language in my writing. Therefore, I need to identify English characters and surround them ...

Utilize jQuery's .append() function to dynamically insert content into your webpage

I currently have tab elements set up like this: <div class="tab-pane fade active in" id="tab-a"> </div> To populate the content of that tab with a JavaScript string array, I am using the following code snippet: var full_list = ""; for (var ...

Encountered an unforeseen character 'u' in the initial position of the JSON while attempting to create a plugin

I seem to be encountering some issues with my code. Whenever I attempt to run the script in the developer kit, an error is thrown: unexpected token u in JSON at position 0... funciones.js $(document).ready(function (){ $("#btn1").click(funct ...

Establish a many-to-many relationship in Prisma where one of the fields is sourced from a separate table

I'm currently working with a Prisma schema that includes products, orders, and a many-to-many relationship between them. My goal is to store the product price in the relation table so that I can capture the price of the product at the time of sale, re ...

Using Javascript closures for managing asynchronous Ajax requests within for loops

Let's consider the arrays provided below. var clients = ['a','b']; var reports = ['x','y','z']; var finalData = []; Now, I aim to iterate through them in a specific manner as shown. for(var i=0;i< ...

Occurrences repeating several times following the incorporation of fresh content into the DOM

I am facing an issue with my plugin. I have implemented an update method to handle new elements added to the DOM. Initially, everything works perfectly without any errors or issues. However, when a new element (div with class "box") is added to the DOM, th ...

Enhancing HTML "range" element with mouse scroll functionality for incrementing values in step increments

I'm working on developing a scroll feature that operates independently from the main window's scrolling function. I aim to trigger specific events in the primary window based on interactions with this separate scrollbar. The only solution I coul ...

Guide: Highlighting a selected link in Navigation without redirecting the page can be achieved in AngularJS by utilizing

I have a list of links that I want to be able to highlight when clicked without redirecting to the page. Below is the code snippet: HTML <ul class="nav nav-list"> <li ng-repeat="navLink in navLinks" ng-class="navClass('{{navLink.Title ...

The page is not responding after closing the modal dialog

My web application is built using Spring Boot for the backend and Thymeleaf for the front end. The app displays all available groups for users to review. When a user clicks on a group, the documents within that group are listed in a tabular form. Clicking ...

Personalized text field in date selector using Material UI

Hey there, I've been incorporating Material UI into my react project, specifically utilizing their recommended Material UI Pickers for a date picker. In order to maintain consistency with the rest of my form fields, I'm attempting to customize th ...

The OrbitControls function is not able to be instantiated as a constructor

I've been working on creating a WebVR environment for the past week using Three.js, but I'm having trouble getting the VR controls to function correctly. Here are some of the things I've tried: 1. Adding packages in my node_modules and imp ...

Vue app hosted on Firebase displays a blank page when user logs in

After deploying my Vue2 project to Firebase hosting server, visitors are required to log in to access the other pages. The issue is that once a user successfully logs in, they are redirected to the next page but it appears blank. Below is what the firebas ...

What is the significance of the A tag when parsing a URL?

So, I encountered a problem that involved parsing a URL to extract the hostname and pathname, then comparing the extracted pathname with a string. If you need help with this issue, check out this post: How do I parse a URL into hostname and path in javasc ...

When I try to use Node.js and Express, I encounter an issue where I receive the

I recently developed a basic application. Everything was running smoothly until I decided to organize the code using an MVC template. However, now when you visit localhost:3000/add-service, you are greeted with a "Cannot Get /add-service" error message. W ...

Transferring data from AJAX to PHP

I am currently developing a project in PHP. I have created an associative array that functions as a dictionary. Additionally, I have a string containing text with placeholders for keys from the array. My goal is to generate a new String where these key wor ...

Why does everything seem to move in sync with the table's scrolling?

I recently had an issue resolved that fixed most of my concerns: I needed to make three separate edits, and now when I reintroduce the other two edits, they are included within the table section and scroll along with the table instead of being stuck beneat ...

Unable to export Interface in Typescript - the specific module does not offer an export named Settings

I am encountering an issue while trying to export/import an interface in Typescript. The error message I receive is causing confusion as I'm unsure of where I went wrong. Uncaught SyntaxError: The requested module '/src/types/settings.ts' ...

Unlock the power of VueJS with advanced checkbox toggling for array data

I have encountered an issue while working with VueJS regarding the implementation of two features for a set of checkboxes. Initially, the checkboxes are generated dynamically. I am in need of a master 'toggle' checkbox that can toggle the stat ...

React and Rails are not playing nice when it comes to AJAX POST requests - all

I'm currently facing an issue while setting up this AJAX POST request in my react component to interact with my rails api controller. The browser console shows a 404 error and I am unable to trigger the pry debugger. react/src/pages/HomeIndex.js ge ...