Here是一个普朗克来证明我的问题。
如果看起来这应该是两个单独的问题,我道歉,但在我看来,我的问题是相关的。
我有一个需要姓名和电子邮件地址的表单,并且在提交时,除了HTML电子邮件模板之外,还会将这些表单发送到我的后端。这是我的表单的缩写版本:
<form novalidate id="send-email" data-ng-controller="SendListController" ng-submit="sendEmail()">
<div class="form-group">
<!-- Hidden input populated with compiled HTML from the controller -->
<input type="hidden" id="htmlTemplate" name="htmlTemplate" ng-value="form.compiledHtml" data-ng-model="form.compiledHtml">
</div>
<div class="form-group" ng-class="{'has-error':form.name.$invalid && form.name.$dirty}">
<input type="text" class="form-control" id="name" name="name" placeholder="Full Name" data-ng-model="form.name" required>
<span class="help-block has-error" ng-if="form.name.$dirty">this field is required</span>
</div>
<div class="form-group">
<button type="submit" ng-disabled="loading">
<span ng-show="!loading">
<span class="glyphicon glyphicon-send"></span> mail it!
</span>
<span ng-show="loading">
<span class="fa fa-spinner fa-spin" ng-show="loading" ></span> sending . . .
</span>
</button>
</div>
</form>
loading
和!loading
功能正常运行,我的隐藏输入正确填充,我与后端的通信也很好。错误类正被添加到元素中,但表单错误永远不会显示,即使所需的输入具有类ng-dirty
和ng-invalid
,表单也会提交。
这是我的控制器(顺便说一句,我真的不喜欢看JS中的所有HTML标记,所以如果有人有更好的想法,请告诉我):
app.controller('SendListController', ['$scope', 'list', '$http', '$compile', '$timeout', 'toastr', function ($scope, list, $http, $compile, $timeout, toastr)
{
$scope.form = {};
$scope.loading = false;
var container = angular.element('<div></div>');
// list is a service
$scope.list = list;
container.html(
'<h1>{{list.listTitle}}</h1>' +
'<ul>' +
'<li data-ng-repeat="item in list.show()">' +
'<span> {{item.DisplayName}} — </span>' +
'<span> {{item.Description}} — </span>' +
'<span> {{item.Count}} {{item.CountText}} — </span>' +
'<span> ${{item.Price}} </span>' +
'</li>' +
'</ul>'
);
$compile(container)($scope);
$timeout(function () {
$scope.form.compiledHtml = container.html();
// htmlToPlaintext() is a private method whose definition I have not
// included here. Trust that it works.
$scope.form.plainText = htmlToPlainText(container.html());
});
$scope.sendEmail = function()
{
$scope.loading = true;
$http.post('/mail-it', $scope.form)
.success(function (response)
{
if (response.successMessage)
{
toastr.success('Success', response.successMessage);
}
else
{
toastr.warning(response.errorMessage);
}
$scope.form = {};
$scope.loading = false;
})
.error(function (response)
{
toastr.error('Error', 'Uh-oh! Something went wrong. Try again!');
$scope.loading = false;
});
}
同样,一切正常(除了我们都知道,并不意味着它的好或正确),除了表单验证。这是否与我注入编译的HTML有关,在任何一种情况下,是否有更好的方式将该模板与我的表单一起发送?