Reputation: 191
I am working on a MEAN stack app which fetches mappings from mongodb
and displays it in the table. I am using a filter to iterate over the map. Following are the code snippets:
For Controller:
app.controller('MainCtrl', function($scope) {
$scope.data = new Map();
$scope.data.set("prop1","as");
$scope.data.set("prop2","ssas");
});
For Filter:
app.filter('fromMap', function() {
return function(input) {
var out = {};
input.forEach((v, k) => out[k] = v);
return out;
}
});
and HTML:
<body ng-controller="MainCtrl">
<table>
<tr ng-repeat="(key, val) in data | fromMap"><td>{{key}}</td><td>{{val}}</td></tr>
</table>
</body>
What I want to achieve is to both key & value editable. I tried setting ng-model for both key & value in as
<td><input type="text" class="form-control" ng-model="data[key]"></td>
<td><input type="text" class="form-control" ng-model="data[val]"></td>
but this creates an empty text box in both the column. How to set the value in the text field?
Upvotes: 1
Views: 941
Reputation: 13488
angular.module('app', []).controller('ctrl', function($scope) {
$scope.data = new Map();
$scope.data.set("prop1", "as");
$scope.data.set("prop2", "ssas");
$scope.out = [];
$scope.data.forEach((v, k) => $scope.out.push({
key: k,
value: v
}))
$scope.print = function() {
var out = {};
$scope.data.forEach((v, k) => out[k] = v);
return out;
}
$scope.$watch('out', function(newVal, oldVal) {
for (var item of newVal) {
var oldItem = oldVal.filter(x => x.key == item.key)[0];
if (!oldItem) {
$scope.data.delete(oldVal[newVal.indexOf(item)].key);
$scope.data.set(item.key, item.value);
return;
} else {
if (oldItem.value != item.value) {
$scope.data.set(item.key, item.value);
return;
}
}
}
}, true)
})
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js">
</script>
<div ng-app='app' ng-controller='ctrl'>
<ul>
<li ng-repeat='item in out'>
<input type='text' ng-model='item.key' />
<input type='text' ng-model='item.value' />
</li>
</ul>
{{print() | json}}
</div>
Upvotes: 1