AngularJS: ng-repeat with key value - updating object

不想你离开。 提交于 2019-12-04 01:55:27
<div ng-controller="mainCtrl">    
<div ng-repeat="record in records">

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

And the JS:

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

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

This option works with object:

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

Not a brilliant, but it works.

After scratching my head to the bone, i find a way to update object key names. It is a bit twisted but it works for me.

replace

<input ng-model="key" />

with

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

you will need the 'lineKey' directive just to keep focus on your input

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();
        }
    };
});

finally, add the 'update_key' method to your controller

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]; }
        }
    };
}
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!