我有一个在提交html表单时执行的函数,如果在处理服务器上的表单时出错,则错误将作为json返回。我想向用户显示这些错误,但由于某种原因,我的错误div容器上的ng-show永远不会显示。
Html代码:
<form class="form-horizontal" role="form" name="registerForm" ng-controller="RegisterController as register" ng-submit="registerForm.$valid && register()" novalidate>
<div class="form-group">
<div class="col-md-3">
<label for="email">Email: </label>
</div>
<div class="col-md-9">
<input type="email" id="email" name="email" ng-model="d.email" class="form-control" ng-required/>
</div>
</div>
<div class="form-group">
<div class="col-md-3">
<label for="password">Password</label>
</div>
<div class="col-md-9">
<input type="password" id="password" name="password" ng-model="d.password" class="form-control" ng-required/>
</div>
</div>
<div class="form-group">
<div class="col-md-3">
<label for="confPassword">Confirm Password</label>
</div>
<div class="col-md-9">
<input type="password" id="password_confirmation" name="password_confirmation" ng-model="d.password_confirmation" nx-equal-ex="d.password" class="form-control" ng-required/>
</div>
</div>
<span class="help-block errorMessages" ng-show="d.errors.length">
<div class="alert alert-danger">
<strong>Whoops!</strong> There were some problems with your input.<br><br>
<ul class="list">
<li ng-repeat="error in d.errors"><% error %></li>
</ul>
</div>
</span>
<div class="form-group">
<div class="col-md-12">
<br/>
<hr>
<button class="big-red-button" type="submit">Register <i class="glyphicon glyphicon-chevron-right"></i></button>
</div>
</div>
</form>
Register.js控制器:
(function() {
angular.module('vendor').controller('RegisterController', ['$http', '$scope', function($http, $scope) {
$scope.d = {};
$scope.d.errors = {};
$scope.register = function() {
$.ajax({
type: "POST",
url: "/auth/register",
headers : {
'X-XSRF-Token': $("meta[name='csrf_token']").attr("content")
},
data: {
email: $scope.d.email,
password: $scope.d.password,
password_confirmation: $scope.d.password_confirmation
},
dataType: 'json',
success: function(data) {
alert(result[0]);
},
error: function(xhr, status, err) {
var responseJSON = JSON.parse(xhr.responseText);
$scope.d.errors = responseJSON;
//alert($scope.d.errors.name);
}
});
};
}]);
}) ();
当错误返回到页面时没有任何反应,ng-show不显示代码。
答案 0 :(得分:0)
使用数据绑定显示错误:
<ul class="list">
<li ng-repeat="error in d.errors"><% error %>{{error}}</li>
</ul>
答案 1 :(得分:0)
我可能错了,但$ .ajax是一个jQuery?如果是的话,
角度范围之外的任何东西都需要手动触发摘要周期。
所以你有两个选择。
在$ scope.d.errors = responseJSON add 之后
$scope.$apply();
或使用$http
$http.post({
type: "POST",
url: "/auth/register",
headers : {
'X-XSRF-Token': $("meta[name='csrf_token']").attr("content")
},
data: {
email: $scope.d.email,
password: $scope.d.password,
password_confirmation: $scope.d.password_confirmation
}
}).success(
function(data) {
alert(data[0]);
}
).error(function(err, status, headers, conf) {
$scope.d.errors = data;
//alert($scope.d.errors.name);
});