10

我正在使用 ng-repeat 渲染 key:value 对象数组,如下所示:

<div ng-controller="mainCtrl">    
  <div ng-repeat="record in records">
    <div ng-repeat="(key, value) in record">
        <input ng-model="key" />: <input ng-model="value" />
    </div>
  </div>
</div>

JS:

var mainCtrl = function($scope){
$scope.records = [
        {'key1':'val1'},
        {'key2':'val2'}
        ];
}

问题是无法通过输入标签更新键和值。出于某种原因,它在使 ng-repeat 迭代 (key,value) 后成为一种绑定方式。

小提琴:http: //jsfiddle.net/BSbqU/1/

我怎样才能使它成为双向绑定?还是我应该以与嵌套 ng-repeat 不同的方式解决这个问题?

4

3 回答 3

7
<div ng-controller="mainCtrl">    
<div ng-repeat="record in records">

        <input ng-model="record.name" />: <input ng-model="record.value" />
    </div>
</div>

和 JS:

var myApp = angular.module('myApp', []);

var mainCtrl = function($scope){
$scope.records = [
{'name':'key1','value':'val1'},
{'name':'key2', 'value':'val2'}
        ];
}
于 2013-05-11T11:25:52.257 回答
6

此选项适用于对象:

<div ng-controller="mainCtrl">    
  <div ng-repeat="record in records">
    <div ng-repeat="(key, value) in record">
        <input ng-model="key" />: <input ng-model="record[key]" />
    </div>
  </div>
</div>

不是很出色,但它确实有效。

于 2016-05-12T09:14:41.610 回答
0

在挠头之后,我找到了一种更新对象键名的方法。这有点扭曲,但它对我有用。

代替

<input ng-model="key" />

<input type="text" ng-model="key" ng-change="update_key(record,key,$index)" line-key/>

您将需要“ lineKey ”指令来专注于您的输入

var app = angular.module('myApp',[]);
var focus_key=-1;
app.directive('lineKey', function () {
    return function (scope, element, attrs) {
        if(focus_key==scope[attrs.ngModel]){
            focus_key=-1;
            element[0].focus();
        }
    };
});

最后,将“ update_key ”方法添加到您的控制器

app.controller('mainCtrl',['$scope'],function($scope){
        $scope.records = [
        {'key1':'val1'},
        {'key2':'val2'}
    ];
    $scope.update_key=function(obj,new_key,id){
        var keys    = Object.keys(obj);
        var values  = Object.values(obj);
        var old_key = keys[id];
        if(keys.indexOf(new_key)==-1&&new_key.length>0){
            // clear ...
            for(var i=0,key;key=keys[i];i++){   delete obj[key];    }
            keys[id]=new_key;//... change key value ...
            focus_key=new_key;//... notify to keep focus on modifyed input ...
            // ... and refill to preserve the position in the object list
            for(var i=0,key;key=keys[i];i++){   obj[key]=values[i]; }
        }
    };
}
于 2016-10-01T05:45:11.693 回答