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

时间:2014-01-02 00:18:14

标签: javascript angularjs

我正在尝试将一些服务器端表单验证添加到我的angular js app。我很难使表单字段无效并显示错误消息。

我的基本应用程序如下所示:

我有一个带有控制器的模型'客户'

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();
}]);

和表单视图

<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>

和这样的应用程序

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/"
        });

});

是否有人能够向我提供一个示例,说明我应该如何将abn字段设置为无效并显示错误消息?

1 个答案:

答案 0 :(得分:5)

显示错误的方法应该是这样的:

$error.server更改为$invalid

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

我为ng-invalid类添加了一个样式,并在按下保存按钮后创建了一个plunkr,其中字段变为红色并显示errorMessage。在$scope.errors上设置属性时还有另一个错误,因为它为空。

http://plnkr.co/fDWF5g

相关问题