ng-repeat 在对象属性上,但在输入后散焦输入框 [英] ng-repeat on object properties but defocuses input box after typing

查看:25
本文介绍了ng-repeat 在对象属性上,但在输入后散焦输入框的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在使用 ng-repeat 将表单元素绑定到我拥有的自定义对象的属性,例如:

 $scope.myObject = {'字体大小':10,'文本轮廓宽度':2,'边框颜色':'黑色','边框宽度':3,'背景色': '白色','颜色':'#fff'}

HTML:

<p>{{key}} : {{prop}}</p><input type='text' ng-model='myObject[key]'>

但是,每次我尝试在输入框中输入值时,文本框都会被取消选择,我必须重新选择它才能继续输入.

是否有另一种方法可以对对象进行双向绑定,以便我可以自由键入?

这是JSFiddle:http://jsfiddle.net/AQCdv/1/

解决方案

输入不集中的原因是 Angular 在每次 myObject 更改时重建 DOM.您可以专门指示 ng-repeat 按键进行跟踪,这样就不会发生不良行为.此外,这将需要在较新版本的库上使用 1.1.5:

function MyCtrl($scope) {$scope.myObject = {'字体大小':10,'文本轮廓宽度':2,'边框颜色':'黑色','边框宽度':3,'背景色': '白色','颜色':'#fff'}}

<script src="http://code.angularjs.org/1.1.5/angular.min.js"><;/脚本><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]'>

更新小提琴.

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.

这篇关于ng-repeat 在对象属性上,但在输入后散焦输入框的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
前端开发最新文章
热门教程
热门工具
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆