ng-重复对象属性,但在键入后使输入框散焦

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

本文关键字:输入 对象 属性 ng-      更新时间:2023-09-26

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

 $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>

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

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

下面是 JSFiddle:http://jsfiddle.net/AQCdv/1/

输入没有聚焦的原因是 Angular 在每次 myObject 更改时都重建了 DOM。您可以专门指示 ng-repeat 按键跟踪,这样就不会发生不需要的行为。此外,这将需要在较新版本的库上提供 1.1.5:

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>

更新的小提琴。

这可以通过指令来解决。我创建了一个名为 customBlur 的指令,但它可以随心所欲地调用,前提是它在 HTML 中匹配。在这里查看小提琴: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; //ignore check boxes and radio buttons
            elm.unbind('input').unbind('keydown').unbind('change');
            elm.bind('blur', function() {
                scope.$apply(function() {
                    ngModelCtrl.$setViewValue(elm.val());
                });
            });
        }
    };
});

和要使用的 HTML 指令,例如

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

此指令的作用是取消绑定生成模型更新的事件,从而导致文本字段失去焦点。现在,当文本字段失去焦点(模糊事件)时,模型将更新。