Loop through object properties using ng-repeat but remove focus from input box after typing

I have been utilizing ng-repeat to connect form elements to the attributes of a custom object I've created. Here's an example:

 $scope.myObject = {
            'font-size': 10,
            'text-outline-width': 2,
            'border-color': 'black',
            'border-width': 3,
            'background-color': 'white',
            'color': '#fff'
    }

HTML:

<div ng-repeat='(key, prop) in myObject'>
    <p>{{key}} : {{prop}}</p>
    <input type='text' ng-model='myObject[key]'>
</div>

However, each time I attempt to input a value into the text box, it gets deselected and I must click on it again to continue typing.

Is there an alternative method for achieving this two-way binding with an object that allows for seamless typing?

Check out the JSFiddle here: http://jsfiddle.net/AQCdv/1/

Answer №1

Angular caused the inputs to lose focus due to its constant rebuilding of the DOM with every change in myObject. To prevent this issue, you can specify ng-repeat to track by key. Additionally, make sure you are using version 1.1.5 or newer of the Angular library:

function MyCtrl($scope) {
  $scope.myObject = {
    'font-size': 10,
    'text-outline-width': 2,
    'border-color': 'black',
    'border-width': 3,
    'background-color': 'white',
    'color': '#fff'
  }
}
<script src="http://code.angularjs.org/1.1.5/angular.min.js"></script>
<div ng-app ng-controller="MyCtrl">
  <div ng-repeat='(key, prop) in myObject track by key'>
    <p>{{key}} : {{prop}}</p>
    <input type='text' ng-model='myObject[key]'>
  </div>
</div>

Check out the updated fiddle here.

Answer №2

One effective solution is to utilize a directive. A custom directive was developed under the name customBlur, although you have the flexibility to rename it as needed, ensuring consistency in your HTML structure. For reference, please check out this jsfiddle: http://jsfiddle.net/AQCdv/3/

angular.module('app', []).directive('customBlur', function() {
    return {
        restrict: 'A',
        require: 'ngModel',
        link: function(scope, elm, attr, ngModelCtrl) {
            if (attr.type === 'radio' || attr.type === 'checkbox') return; //exclude radio buttons and checkboxes

            elm.unbind('input').unbind('keydown').unbind('change');
            elm.bind('blur', function() {
                scope.$apply(function() {
                    ngModelCtrl.$setViewValue(elm.val());
                });
            });
        }
    };
});

To implement the directive in HTML:

<input type='text' ng-model='myObject[key] ' custom-blur>

This directive effectively removes the events responsible for updating the model, thereby preventing the text field from losing focus. Consequently, when the text field loses focus (triggering the blur event), the models are updated accordingly.

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

Troubleshooting Angular 2: Instances of Classes Not Being Updated When Retrieving Parameters

I am facing an issue with the following code snippet: testFunction() { let params = <any>{}; if (this.searchTerm) { params.search = this.searchTerm; } // change the URL this.router.navigate(['job-search'], {q ...

Populate data in a third-party iframe using a Chrome Extension

Having trouble with my chrome extension that autofills form inputs because the iframe is loaded from a different source, resulting in Chrome restricting script access to the iframe. There are numerous questions about this on SO already. I recently discove ...

Implementing a feature to close the drawer component from the main page by clicking on the menu button in React-js

Just starting out with reactjs and I've got my main page set up like this: <div > <AppBar position="flex" style={{backgroundColor:'#1A437E'}}> <Toolbar> <IconButton edge="end" color= ...

What is the best way to include a file attachment using a relative path in Nodemailer?

I am currently utilizing the html-pdf converter plugin to transform an HTML page into a PDF file. After conversion, this plugin automatically saves the PDF to the downloads folder. When I attempt to attach a PDF to a nodemailer email, my code looks someth ...

Display the output from a JavaScript code snippet on the console

Is there a simple way to incorporate JavaScript into RMarkdown and display the results in the knitted document without adding a lot of extra code? I discovered that I can create new div elements and attach them to the document's DOM, but this method s ...

I want the navigation bar to appear only upon scrolling, but when I refresh the page it is already visible, and then vanishes as I start scrolling

I'm working on a project where I want the navigation bar to only appear after scrolling a certain distance down the page. However, I've noticed that when I refresh the browser, the navigation bar appears immediately and then disappears once I sta ...

Removing a specific item from an array

state = { filters: ['all'] } this.state.filters.includes('humans') ? this.state.filters.filter(val => val !== 'humans') : this.state.filters.push(dropdown) I have a condition set up so that when I click on a button, ...

When I tap on it, the box should shift its position

Here's a conundrum for you. I have a box that I want to move 200px to the left when clicked, but I'm struggling to make it work. Can someone please lend a hand and point out where I'm going wrong? <style> .box { width: 200px; ...

Delays can occur in CSS when transitioning an element's visibility from `visible` to `hidden`

I have a navigation bar with three elements arranged horizontally from left to right: socialMediaIcons, logoArea, and navBarOptionsList. I've written JavaScript and CSS code that changes the visibility of socialMediaIcons and navBarOptionsList to hid ...

Retrieving individual data elements from an array with the help of the .find() method

I am struggling to display specific details of an object within an array by using .find() method, but I keep receiving undefined as the output. Below is the code snippet where I attempted this, when I log the ID, I can see a value, however, when I try to ...

Lagging speeds in client-side template rendering using Rivets.js

I have a function that renders an array of around 1000 objects, but the html bindings are causing significant performance issues. It currently takes about 5 seconds to complete rivets.bind(). Does anyone have any recommendations for improving performance? ...

IE11 not processing jQuery ajax response correctly

While creating a login page using jQuery/AJAX, my code is functioning perfectly on all browsers except for IE11. In IE11, I am encountering the following exception: SCRIPT7002: XMLHttpRequest: Network Error 0x800c0008, The download of the specified resour ...

Angular 6 data modification update: What you need to know

Whenever a new response is added to the array of 15 responses, I aim to dynamically update the view without requiring the page to refresh. addResponseToItemArray(res: DashboardInfo[]): void { this.item.push([]); // ERROR this.item.push([]); ...

Guide on eliminating commas by utilizing the replace function in Angular

Check out the code snippet here: https://stackblitz.com/edit/angular-w5ecbw?file=src/app/app.component.ts item.component.ts ngOnInit() { const data = ['.23.2 ms','.23.001 ms', '.23.81 ms', '192,101.02 ms', &apo ...

Execute jQuery code only when a child element within the parent container is clicked

Within a div section, I have included various child controls like dropdowns and check boxes. I am seeking to implement some jQuery code that will be triggered when any of the child elements are clicked, excluding clicks on the empty space within the div. ...

Guide to retriecing a state in Next.js 14

Check out my code below: "useState" // firebase.js import firebase from "firebase/app"; import "firebase/auth"; // Import the authentication module export default async function handler(req, res) { if (req.method !== " ...

The jsonGenerator is unable to process strings containing spaces

Hey, I'm having trouble passing a string with whitespaces to my JavaScript function using jsonGenerator. Here's the code snippet: jGenerator.writeStringField(cols[8], ap.getContentId() != null ? "<img src='img/active.png' onclick=au ...

Tips for creating a see-through scrollbar in React?

Lately, I've been experimenting with adding overflow-Y: scroll to materialize collections in order to maintain a fixed wrapper height. However, my latest challenge has been figuring out how to make the scrollbars transparent. I've come across sug ...

Having difficulty retrieving information from the interactive spreadsheet

I am encountering an issue while trying to retrieve the values from Handsontable, and the error message displayed is: Uncaught ReferenceError: hot is not defined Despite having defined hot variable, I am puzzled as to why this error is occurring. Below i ...

Organize Your Data in AngularJS After Completing Calculations in the View

I am wondering about incorporating math calculations on a view and organizing the values in Angular. While I understand that these calculations can be done beforehand, I am curious if it can be achieved after the fact as well. Here is the link to my jsFidd ...