提交数据后,再添加到数组中,然后显示在表中。如果我在输入文本字段中进行更改,它将被直接反映到表中。
像这样HTML
<body ng-app="crud">
<div ng-controller="ctrl">
<form ng-submit="sub()">
<label for="name">name</label>
<input type="text" name="name" ng-model="myForm.name" />
<br><br>
<label for="contact">contact</label>
<input type="text" name="contact" ng-model="myForm.contact" />
<input type="submit" value="sumit" ng-click="sub" />
</form>
<div>
<table>
<tr ng-repeat="x in data track by $index">
<td>{{x.name}}</td>
<td>{{x.contact}}</td>
<td>
<button type="button" ng-click="edit(x)">Edit!</button>
</td>
</tr>
</table>
</div>
</div>
</body>
JS
var app = angular.module("crud", []);
app.controller("ctrl", ['$scope', function($scope) {
$scope.data = [{
name: "ankur",
contact: 987898
}, {
name: "santosh",
contact: 987678
}, {
name: "tanvi",
contact: 98789877
}];
$scope.count = 0;
$scope.myForm = {};
$scope.myForm.contact = 0;
$scope.myForm.name = "";
$scope.sub = function(myForm) {
$scope.data.push($scope.myForm);
};
}]);
答案 0 :(得分:2)
Angularjs是面向对象的。 不要将同一个对象推入数组,而是复制并推送。那对你有利。
$scope.data.push(angular.copy($scope.myForm));
另一种方式
<form>
<label for="name">name</label>
<input type="text" name="name" ng-model="myForm.name" />
<br><br>
<label for="contact">contact</label>
<input type="text" name="contact" ng-model="myForm.contact" />
<input type="button" value="submit" ng-click="sub(myForm)" />
</form>
在Js
$scope.sub = function(myForm) {
$scope.data.push(myForm);
};