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

Top solution for maintaining smooth navigation across web pages

As I dive into the world of web development, I find myself intrigued by the idea of reusing navigation and banners across multiple web pages. However, despite my research efforts, I have yet to come across a definitive answer. My objective is simple: The ...

Getting Rid of Angular Material Suggestions: A Step-by-Step Guide

<md-autocomplete ng-model="ctrl.searchText" md-selected-item="ctrl.selectedItem" md-selected-item-change="ctrl.selectedItemChange(item)" md-search-text="ctrl.searchText" md-search-text-change="ctrl.searchTextChange(ctrl.searchText)" ...

Can anyone point out where the mistake lies in my if statement code?

I've encountered an issue where I send a request to a page and upon receiving the response, which is a string, something goes wrong. Here is the code for the request : jQuery.ajax({ url:'../admin/parsers/check_address.php', meth ...

What is the process for creating a custom Vue 3 element with incorporating styles for child components?

After experimenting with Vue's defineCustomElement() to develop a custom element, I encountered an issue where the child component styles were not being included in the shadow root for some unknown reason. To address this problem, I took a different ...

Angular 2 encountering an error with the HTTP GET request

I am currently facing some challenges with subscribing to the response while using the http method get request. Below is my service implementation: import { Injectable } from '@angular/core'; import { Http, Response } from '@angular/http&ap ...

Command for DiscordJS to verify users

I have a requirement to develop a verification command using discord.js v12. This command will assign a verified role based on the configuration specified in a config file. Config file: { "token": "my-token", "status": " ...

unable to adjust the maximum height limit

I've been struggling to set a maximum height on the slider I'm currently using. No matter what height value I input, it doesn't seem to take effect. Additionally, I attempted setting the width for the echo img row in the PHP section but enco ...

Save the retrieved data in a variable and pass the entire JSON object as a prop to a React component

Having some trouble with my code. I need the app to fetch a JSON from an API and pass it as a prop so that each component file can use it and display the element on the screen. The issue is, I can't seem to figure out how to store the fetched informa ...

Converting Strings into Variable Names in Vue.js: A Step-by-Step Guide

Hi everyone, I was wondering if there's a way to convert a string into a variable name. For example, I want to convert "minXLabel" to minXLabel so that I can use it within span tags like this: <span>{{minXLabel}</span>. I current ...

What is the best way to extract a specific value from a JSON object?

I'm currently working on building a marketplace using Angular. The main marketplace page is already set up and populated with data from a remote JSON file created with mockapi. However, I've encountered an issue when trying to display a single ra ...

Dealing with a throw er; uncaught 'err' event while configuring a server with nodemon

I am currently in the process of setting up my local server using node.js and nodemon. Initially, everything runs smoothly on localhost, but as soon as I refresh the page or navigate to another page, the server crashes with an 'unhandled error event&a ...

Customizing Attribute for Material UI TextField

I'm currently in the process of adding a custom data attribute to a TextField component like so: class TestTextField extends React.Component { componentDidMount() {console.log(this._input)} render() { return ( <TextField label= ...

Using Javascript to attach <head> elements can be accomplished with the .innerHTML property, however, it does not work with XML child nodes

Exploring new ways to achieve my goal here! I want to include one JS and one jQuery attachment for each head section on every page of my static website. My files are: home.html <head> <script src="https://ajax.googleapis.com/ajax/libs/jquer ...

Setting up a retrieval callback in mongoose and storing it in a global variable

Is there a way to set the value of db as a global variable? I am having trouble with getting the console output of name outside of the findOne function, it keeps showing me undefined. Any suggestions on how to fix this issue? var name; schema.findone({na ...

ngModel.$setValidity is a one-time operation

Currently, I am working on a validation issue with an angular bootstrap ui datepicker popup. I have set the max and min dates for validation, which work when the user selects a date from the calendar. However, if the user manually inputs a date, these vali ...

Is using the new Date function as a key prop in React a good

In my React code, I have been using new Date().getTime() as key props for some Input components. This may not be the best practice as keys should ideally be stable. However, I am curious to know why this approach is causing issues and why using Math.random ...

Issue with displaying jqplot in a jQuery page

Currently, I'm utilizing jqmobile pages for switching between various pages in an html5 application. One of these pages features a jqplot chart. Below is the code snippet: <div data-role="page" id="page-two" data-title="Page 2"> &l ...

Looking for a resolution with NicEditor - Seeking advice on incorporating custom select options

I recently started using NICInline Editor and found a helpful sample at Is there a way to incorporate custom options into this editor? I would like the selected option's value to be inserted right at the cursor point of the Editor Instance. Query: H ...

The Problem of Restoring Column Height in Tabulator 4.6.3 Filters

The Issue After activating and deactivating header filters, the column height does not return to its original state. Is this the expected behavior? Is there a way to reset the column height? Check out this JS Fiddle example: https://jsfiddle.net/birukt ...

What method can we use to temporarily route traffic from one URL to another URL for a specific amount of time?

Is there a way to use javascript/jquery code that will redirect my website to a different domain, but only during specific hours? I'm looking to have the redirection occur between 2 a.m. and 4 a.m., so that it only works for two hours out of the day. ...