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

时间:2017-12-21 11:36:14

标签: javascript html angularjs ionic-framework

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

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

我希望更改,例如    我想将"mainKey1"更改为"newKey1"在ng-repeat

我的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中的键并不起作用,任何人都可以帮助达到预期效果,提前致谢

1 个答案:

答案 0 :(得分:1)

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>