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/
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With