简体   繁体   English

Angular JS将表单字段设置为无效

[英]Angular JS set form field as invalid

I am trying to add some server side form validation to my angular js app. 我正在尝试向我的angular js应用添加一些服务器端表单验证。 I'm having a hard time invalidating the form field and displaying the error message. 我很难使表单字段无效并显示错误消息。

My basic application looks like this: 我的基本应用程序如下所示:

I have a model 'client' with a controler 我有一个带有控制者的模型“客户”

Accounts.controller('Client', ['$scope', 'ClientService', function ($scope, ClientService) {
    $scope.loading = false;
    $scope.errors = null;

    $scope.init = function () {
         $scope.abn = "some value from API call";
    };

    $scope.save = function (client) {
            $scope.form.abn.$setValidity("server", false);
            $scope.errors.abn = "Error message";
    }

    $scope.init();
}]);

and a form view 和一个表单视图

<form name="form">
    <div class="form-group">
        <label>ABN Number</label>
        <input type="text" name="abn" ng-model="client.abn">
        <span ng-show="form.abn.$error.server">{{client.errors.abn}}</span>
    </div>
    <button ng-click="save(client)">Save</button>
</form>

and an app like so 和像这样的应用

var Accounts = angular.module('Accounts', [
    'ngRoute',
    'ui.select2',
    'ui.router'
])
.config(function ($stateProvider, $routeProvider) {
    $routeProvider.otherwise('/404');

    $stateProvider
        .state('client', {
            url: "/client",
            templateUrl: "client",
            controller: 'Client'
        })
        .state('404', {
            url: "/404",
            templateUrl: "/error/e404/"
        });

});

Is someone able to provide me with an example of how I should be setting the abn field as invalid and displaying an error message? 有人能够为我提供一个示例,说明我应如何将abn字段设置为无效并显示错误消息?

The way to display the error should be like this: 显示错误的方式应该是这样的:

changed from $error.server to $invalid : $error.server更改为$invalid

<span ng-show="form.abn.$invalid">{{client.errors.abn}}</span>

I added a style for ng-invalid class and created a plunkr where the field gets red and the errorMessage is displayed, once you press the save button. 我为ng-invalid类添加了样式,并创建了一个plunkr,一旦按下保存按钮,该字段将变为红色并显示errorMessage。 There was also another error when setting a property on $scope.errors because it was null. $scope.errors上设置属性时,还会出现另一个错误,因为该属性为null。

http://plnkr.co/fDWF5g http://plnkr.co/fDWF5g

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM