我有一个包含两个文本框,一个用于获取名称,另一个用于发送电子邮件,还有一个按钮添加新行,添加这两个文本框我正在尝试通过{{1获取名称和电子邮件的所有值但我是Angular的新手
这是我的代码:
JS CODE
AngularJS
HTML
function addrow() {
var table = document.getElementById("emp");
var row = table.insertRow(2);
var name = row.insertCell(0);
var email = row.insertCell(1);
name.innerHTML = "<input id='Name' type='text' value='' name='ename' ng-model='data.ename'>";
email.innerHTML = "<input type='text' value='' name='Email' id='email' ng-model='data.email'>";
}
AngularJS代码
<form name="employees" ng-submit="emp()">
<table id="emp">
<tr>
<td>Employee Name
</td>
<td>Employee Email
</td>
</tr>
<tr>
<td>
<input type="text" id="Name" name="ename" ng-model="data.ename" />
</td>
<td>
<input type="email" id="email" name="email" ng-model="data.email" />
</td>
</tr>
</table>
<button class="btn btn-primary" onclick="addrow();">Add new</button>
<input type="submit" class="btn" />
</form>
答案 0 :(得分:1)
如果您不需要所有条目都可编辑,则可以使用@Brian的解决方案。如果您希望所有这些都可编辑,只需使用ng-repeat
来包装输入:
<form name="employees" ng-submit="emp()">
<table id="emp">
<tr>
<td>Employee Name</td>
<td>Employee Email</td>
</tr>
<tr ng-repeat="emp in employees">
<td><input ng-model="emp.ename" /></td>
<td><input type="email" ng-model="emp.email" /></td>
</tr>
</table>
<button class="btn btn-primary" ng-click="addrow()">Add new</button>
<input type="submit" class="btn" />
</form>
var model1Controller = ["$scope", "$http", function ($scope, $http) {
var employees = $scope.employees = [];
$scope.addrow = function() { employees.push({ /* don't need anything here */ }); };
$scope.emp = function () {
console.log(employees);
}
};
答案 1 :(得分:0)
废弃addrow()
功能文件,将其移至控制器,然后使用ng-repeat
过滤器。 ngRepeatDocs。 Angular在这种情况下的全部目的,就是为你做元素和DOM绑定,这样你就不必编写一个函数来刮取值并插入html。也就是说,我不知道你的提交是否是为了在表格中添加一个人,或者提交是否应该提交你的所有表格数据,你还有另一个按钮(你提到了一个按钮,但我不是在代码中看到一个)将员工添加到表单中。在您清楚了解之前,以下是如何在数据模型中显示每个员工的指南,并使用提交操作将其添加到表单中:
<form name="employees" ng-submit="addrow()" ng-controller="model1Ctrl">
<table id="emp">
<tr ng-repeat="emp in data">
<td> {{ emp.ename }}
</td>
<td>{{ emp.email }}
</td>
</tr>
<tr >
<td>
<input type="text" id="Name" name="ename" ng-model="ename" />
</td>
<td>
<input type="email" id="email" name="email" ng-model="email" />
</td>
</tr>
</table>
你的控制器:
var model1Ctrl = ['$http','$scope',function($http,$scope){
$scope.data = [];
$scope.addrow = function () {
var newEmp = {
ename: $scope.ename,
email: $scope.email
}
$scope.data.push(newEmp); //adds the new employee as an object into your data set
// which ng-repeat will automatically know about, and display in your table
//clear the scope of your inputs so they can be used again
$scope.ename = '';
$scope.email = '';
}
}]