gpt4 book ai didi

javascript - 有没有办法使用 ng-repeat 动态更改对象的键

转载 作者:行者123 更新时间:2023-11-30 20:53:23 25 4
gpt4 key购买 nike

我的 json 对象看起来像这样,

$scope.myObject = {
"mainKey1":{
"name": "x",
"age": "20"
},
"mainKey2":{
"name":"y",
"age":"25"
},
"mainKey3":{
name:"z",
"age":"30"
}
};

例如,我想更改, 我想在 ng-repeat

中将 "mainKey1" 更改为 "newKey1"

我的 html 看起来像这样

<div ng-repeat="(key,obj) in myObject">
<label>Name</label>
<input type="text" name="name" ng-model="obj.name"
placeholder="enetr name"/><br/>

<label>Age</label>
<input type="text" name="age" ng-model="obj.age" placeholedr="enter age" /><br/>

<label>Key </label>
<select ng-options="k for k in keyCollection" ng-model="key" >
</select>
</div>

但看起来直接在 ng-model 中使用 key 不起作用,任何人都可以帮助实现预期结果,提前致谢

最佳答案

angular.module('app', []).controller('ctrl', function($scope) {
$scope.myObject = {
"mainKey1": {
"name": "x",
"age": "20"
},
"mainKey2": {
"name": "y",
"age": "25"
},
"mainKey3": {
"name": "z",
"age": "30"
}
};

$scope.keyCollection = ['newKey1', 'newKey2', 'newKey3'];
for (var key in $scope.myObject)
$scope.keyCollection.push(key);

$scope.changeKey = function(next, ex) {
if (Object.keys($scope.myObject).indexOf(next) == -1) {
var temp = $scope.myObject[ex];
delete $scope.myObject[ex];
$scope.myObject[next] = temp;
}
}

})
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>

<div ng-app='app' ng-controller='ctrl'>

<div ng-repeat="(key,obj) in myObject">
<label>Name</label>
<input type="text" name="name" ng-model="obj.name" placeholder="enter name" /><br/>

<label>Age</label>
<input type="text" name="age" ng-model="obj.age" placeholedr="enter age" /><br/>

<label>{{key}}</label>
<select ng-options="k for k in keyCollection" ng-change='changeKey(temp, key)' ng-model='temp' ng-init='temp=key'></select>
<br>
<br>
</div>
</div>

关于javascript - 有没有办法使用 ng-repeat 动态更改对象的键,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47924119/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com