Reputation: 555
I want to loop over an object's property. Also, there should be a two-way data binding so that any change will change the Object as well.
Both key and value of the object property can be changed from UI and should reflect in the object's structure.
I am able to do it for object's value with ng-model="contents[index]"
but how to do that with object property key e.g. interface in the object will change if I change it on UI.
$scope.contents = {
"interface": "GigabitEthernet",
"interfaceNumber": "1",
"BGPneighborIp": "00.0.112.499",
"BGPremoteAs_[1]": "701",
"BGPneighborIp_[2]": "8.3.112.170",
"BGPremoteAs_[2]": "702"
}
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>
<tbody>
<tr ng-repeat="(index, p1) in contents">
<td>
<input class="form-control" type="text" ng-model="index">
</td>
<td>
<input class="form-control" type="text" ng-model="contents[index]">
</td>
</tr>
</tbody>
Upvotes: 0
Views: 1146
Reputation: 13488
Try this solution:
angular.module('app',[]).controller('test',['$scope', function($scope){
$scope.contents = {
"interface": "GigabitEthernet",
"interfaceNumber": "1",
"BGPneighborIp": "00.0.112.499",
"BGPremoteAs_[1]": "701",
"BGPneighborIp_[2]": "8.3.112.170",
"BGPremoteAs_[2]": "702"
};
$scope.arr = [];
for(var prop in $scope.contents)
$scope.arr.push({oldKey:prop, newKey:prop});
$scope.change = function(item){
$scope.contents[item.newKey] = $scope.contents[item.oldKey];
delete $scope.contents[item.oldKey];
item.oldKey = item.newKey;
}
}])
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>
<div ng-app='app' ng-controller='test'>
<input ng-repeat-start='item in arr' type='text' ng-model="item.newKey" ng-change='change(item)'>
<input type='text' ng-model="contents[item.oldKey]" >
<br ng-repeat-end>
<p>{{contents|json}}</p>
</div>
Upvotes: 1