对对象属性进行ng-repeat,但在键入后将defocuses输入框

时间:2013-10-15 23:35:43

标签: javascript angularjs angularjs-ng-repeat

我使用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/

2 个答案:

答案 0 :(得分:22)

输入未集中的原因是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>

Updated fiddle

答案 1 :(得分:0)

这可以通过指令解决。我创建了一个名为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>

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