【发布时间】:2015-06-25 20:34:13
【问题描述】:
我正在使用一个有点动态的 AngularJS 表单。换句话说,我可以添加输入字段的行等。所以我的方法是从 $scope.formData 空对象开始,封装所有绑定到静态和动态 HTML 表单元素的属性。
AngularJS代码如下:
(function() {
var formApp = angular.module("formApp", []);
formApp.controller("FormCtrl", function ($scope, $timeout) {
$scope.formData = {};
$scope.formData.subscribers = [
{ name: null, email: null }
];
$scope.addSubscriber = function() {
$scope.formData.subscribers.push({ name: null, email: null });
};
});
})();
AngularJS 表单的 HTML:
<body data-ng-app="formApp">
<div data-ng-controller="FormCtrl">
<p>
Name of Topic: <input type="text" data-ng-model="formData.title" placeholder="enter a title" />
</p>
Subscribers:
<button data-ng-click="addSubscriber()">Add subscriber</button>
<table>
<tr>
<th>Name</th>
<th>Email</th>
</tr>
<tr data-ng-repeat="subscriber in formData.subscribers">
<td><input type="text" data-ng-model="subscriber.name" placeholder="enter name" /></td>
<td><input type="text" data-ng-model="subscriber.email" placeholder="enter email" /></td>
</tr>
</table>
<hr style="margin:1em 0;" />
<p>
<em>Debug info</em>: {{ formData }}
</p>
</div>
</body>
注意最后的调试信息部分,它显示了$scope.formData对象及其内容。我在实现此表单的方式上有几个问题。
- 第一次加载页面时,
$scope中没有formData.title属性,但由于它绑定到 Title 输入文本字段,当我开始输入值时,title属性被添加到$scope。但是,当我删除输入文本字段中的值时,formData.title属性仍然作为空字符串存在于$scope中。我想这没关系,但我真的想在提交表单时清理空值或空值。如果这样做很容易,我想在客户端执行此操作,因此服务器端代码不必清理任何内容。 - 使用动态 Subscribers 部分,我可以继续添加任意数量的行,但最终,我想过滤掉客户端上的所有空 subscriber 对象一边。
AngularJS 是否有任何选项可以在进一步处理之前检测和清除$scope 中的空值/空值,例如$http POST?
注意我为此示例设置了jsFiddle。
【问题讨论】:
标签: javascript html angularjs angularjs-scope