我有一个简单的表单,当发布然后出错时我想在div框中向用户反馈屏幕上的错误消息。最好的方法是什么?
到目前为止,这是我的控制器:
.controller("CompanyUserFormCtrl", ['$scope', 'Restangular', 'CbgenRestangular', '$q',
function ($scope, Restangular, CbgenRestangular, $q) {
// Submit form
$scope.submit = function () {
var post_data = {email: $scope.email}
var post_call = CbgenRestangular.all('accounts/create-company').post(post_data)
$q.when(post_call.then(
function (object) {
// on success
},
function (object) {
// on error
// render in a div some error message here <----------
}
))
}
}])
我的表单:
<div ng-controller="CompanyUserFormCtrl">
form stuff
<div class="col-lg-offset-3 col-lg-9">
<button type="button" class="btn btn-default" ng-click="submit()">Register</button>
</div>
</div>
我是否需要一个新的指令,如果可以的话,我能看到一个例子吗?
答案 0 :(得分:2)
向包含错误的div添加 ng-show 指令,并在发生错误时将其值设置为true。
e.g。
<div ng-show='createFailed'>Oh dear - create company failed</div>
并在控制器的错误处理程序中:
$scope.createFailed = true;
答案 1 :(得分:1)
我没有示例,我对Angular很新,但您可以使用ngShow指令:
<div ng-show="error.length">{{error}}</div>
并且喜欢:
$q.when(post_call.then(
function (object) {
// on success
},
function (object) {
$scope.error = object.errorText;
}
))
EDIT2:使用“.length”-version!
答案 2 :(得分:0)
You can use
<label>
Username:
<input type="text" ng-model="user.username" name="username"
required
call-back />
</label>
<ng-messages for="signUpForm.username.$error" ng-if="signUpForm.username.$dirty">
<ng-message when="unique" class="error">This is taken</ng-message>
</ng-messages>
m.directive('callBack', function(isUsernameAvailable) {
return {
restrict: 'A',
require: 'ngModel',
link: function(scope, element, attrs, ngModel) {
ngModel.$asyncValidators.unique = isUsernameAvailable;
}
};
});
m.factory('isExist', function($q, $http) {
return function(username) {
var deferred = $q.defer();
$http.get('/api/emp/' + username).then(function() {
// Found the user, therefore not unique.
deferred.reject();
}, function() {
// User not found, therefore unique!
deferred.resolve();
});
return deferred.promise;
}
});