Avoid updating the input from ng-model while it is being edited

There are times when my model.field can be altered by both user input into an input field and by other functions running in the background. However, I want to handle situations where changes made by the user take precedence over modifications made by those background functions. For instance:

$scope.model = {
    field: 'val1'
}

This is the HTML code:

<input ng-model="model.field" ...>

For example:

  • The initial value of model.field is 'val1'
  • The user begins editing the input (it becomes active)
  • While the user is typing, the model updates to 'val2' through a background function
  • Despite the change in the model, the input still displays 'val1'
  • Any key pressed by the user during this time (from 1 to A) replaces the current content in model.field.
  • As a result, the new value of model.field becomes 'valA'

Answer №1

A $formatter can be added to handle ignoring the model when the element is in focus and it seems to be effective:

angular.module('myApp').directive('ngModelIgnoreWhenActive', function() {
    return {
        require: 'ngModel',
        restrict: 'A',
        link: function(scope, element, attributes, ngModelCtrl) {

            //Keeping track if the element has focus
            scope.hasFocus = false;
            element.on('focus', function(event) {
                scope.hasFocus = true;
            });
            element.on('blur', function(event) {
                scope.hasFocus = false;
            });

            //Formatting value before displaying it
            // If focused, maintain current value
            var myFormatter = function(newValue) {
                return scope.hasFocus && element && element[0] ? element[0].value : newValue;
            }

            ngModelCtrl.$formatters.push(myFormatter);
        }
    };
});

The directive can then be applied to relevant input fields like this:

<input ng-model="model.field" ng-model-ignore-when-active>

This code was inspired by the extends-ng-model timestamp formatter provided at: https://github.com/Plippe/extends-ng-model/blob/master/src/extends-ng-model/ng-model-formatter-parser/ng-model-timestamp.js

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

New button attribute incorporated in AJAX response automatically

data-original-text is automatically added in ajax success. Here is my code before: <button type="submit" disabled class="btn btn-primary btn-lg btn-block loader" id="idBtn">Verify</button> $(document).on("sub ...

Is it possible to alter the page color using radio buttons and Vue.js?

How can I implement a feature to allow users to change the page color using radio buttons in Vue.js? This is what I have so far: JavaScript var theme = new Vue({ el: '#theme', data: { picked: '' } }) HTML <div ...

"Retrieving the most recent data within an ng-repeat directive using AngularJS

I am facing an issue with ng-repeat in my application. It successfully fetches values from the database and displays them in input text fields. However, when I update these values and click the save button, the updated values are not being saved. Can someo ...

Combining PHP, Javascript, and Ajax all in one powerful code snippet

Would it be considered poor coding practice to combine PHP, JavaScript, and AJAX in the same block of code? For example: <?php $randNum = rand(1,10) if ($randNum <= 5) { echo "Enemy got the jump on you! <script> enemyTurn() </script& ...

Display the initial x list items without utilizing ngFor in Angular 2

In the template, there are 9 <li> elements, each with a *ngIf condition present. It is possible that 5 or more of them may return true, but the requirement is to only display the first 4 or less if needed. Priority is given to the order of the < ...

Troubleshooting a Form Validation Issue with React's useState Hook

I am currently working on form validation for a project. The form includes two essential elements: a textbox for messages and a textbox for recipients. These elements are controlled by state.message (a string) and state.recipients (an array). The state var ...

"Refreshing UI-View with AngularJS and UI-Router: A Guide on Reloading Your

I am struggling with Angular UI-Router as I am encountering an issue where the state is not being reloaded. Here is a snippet of my code: app.config(function ($urlRouterProvider, $stateProvider) { $urlRouterProvider.otherwise("/home"); $stateProvi ...

What led the Typescript Team to decide against making === the default option?

Given that Typescript is known for its type safety, it can seem odd that the == operator still exists. Is there a specific rationale behind this decision? ...

Unraveling unicode escape sequences in JavaScript strings

My code includes a string like \uC88B\uC544\uC694. When I use this string in a node repl (v7.4.0), it displays '좋아요' correctly. However, when I try to use the same string in the following code snippet, it does not work as ex ...

Obtaining variable content from a JavaScript function

Learning JS with documentation has been a challenging journey for me. The concept of variables inside and outside a function still confuses me. I'm interested in creating a module that allows me to reuse code written in different parts of my program ...

JavaScript appendChild method not functioning properly with dynamically created image elements in JavaScript code

I recently encountered an issue while working on a website project. I was trying to create an img element using JavaScript, but ran into a problem when I tried to add the src attribute and then use the appendChild function. I'm unsure if I am missing ...

Show information from JSON based on the provided parameter

I'm trying to display JSON data based on a parameter passed through state params. However, when using the underscore library, the array is not showing anything. I need help checking the controller code for any issues or if there's an alternative ...

What is the best way to eliminate duplicate values within a v-for array?

To eliminate duplicate values, I wrote the following code: vue <div class="col-md-6" style="float: left"> <ul class="list-group"> <li class="list-group-item" :class="{ active: ind ...

Utilizing functions as arguments in AngularJS 1.5 directives

app.controller('myController', [ '$scope', function ( $scope ) { $scope.doSum = function(x, y){ console.log(x+y); }; } ]); <cmp data-fn="doSum(x, y)"></cmp> app.directive('cmp&apo ...

Calculating every number within a range of dates and storing them in the format of [day, hour]

Given two date pairs represented as numbers [hour, weekday], where hour ranges from 0-23 and weekday ranges from 1-7. I am tasked with generating all the hours in between each pair. For example, if given [13, 2] and [2, 3], the output would be: [13,2] [14 ...

The property 'get' cannot be accessed due to its undefined or null reference

I have encountered a seemingly simple issue while working on my project. The error message I am receiving is: Unable to get property 'get' of undefined or null reference This error occurs when I try to make a call to my API from the controller ...

Is it possible for Vue js to display an image from the /dist/ directory even if it is not present?

Currently, I am in the process of learning Vue.js + webpack and have started a project by following these steps: f:www\> npm install -g vue-cli f:www\> vue init webpack-simple my-project f:www\> cd my-project f:www\> npm in ...

Passing predefined functions to asynchronous functions can be achieved by simply defining the

I am facing a challenge in passing a predefined function within an async function. The piece of code below is functioning flawlessly: async.auto({ getAccessToken: function (callback) { let x = { access_token: signToken({ userId: u ...

Parameters for MongoDB search queries

I am currently working with a MongoDB query on a specific collection. Here is the structure of the query: common.db.collection('vb.vbStats').find({uid:uid, "vbs.vbNID":vbNID}, {"vbs.$":1}).toArray(function(err, result) {....} The collection I a ...

Updating an SVG after dynamically adding a group with javascript: a step-by-step guide

Currently, I am working on a circuit builder project using SVG for the components. In my HTML structure, I have an empty SVG tag that is scaled to full width and height. When I drag components from the toolbar into the canvas (screen), my JavaScript functi ...