AngularJS:带键值的ng-repeat - 更新对象

时间:2013-05-11 09:39:12

标签: angularjs model-binding angularjs-ng-repeat

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

<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迭代(键,值)后,它成为单向绑定。

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

如何将其设为双向绑定?或者我应该以不同的方式处理此问题,然后嵌套ng-repeat?

3 个答案:

答案 0 :(得分:6)

<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'}
        ];
}

答案 1 :(得分: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>

不是很棒,但它有效。

答案 2 :(得分: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]; }
        }
    };
}