Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

ng-repeat on object properties but defocuses input box after typing

I am using ng-repeat to bind form elements to the properties of a custom object I have, 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, every time I try to type in a value into the input box, the text box gets deselected and I have to reselect it to keep typing.

Is there another way to do this two-way binding to an object so that I can type freely?

Here is the JSFiddle: http://jsfiddle.net/AQCdv/1/

like image 587
user1027169 Avatar asked Oct 15 '13 23:10

user1027169


1 Answers

The reason inputs were unfocused is that Angular rebuilt the DOM on every myObject change. You can specifically instruct ng-repeat to track by key, so undesired behavior won't happen. Also, this will require 1.1.5 on newer version of 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>

Updated fiddle.

like image 128
Klaster_1 Avatar answered Nov 15 '22 19:11

Klaster_1