表单元素值更改后的Angular JS验证

时间:2015-03-15 06:23:50

标签: javascript jquery html angularjs validation

这是我在这里的第一篇文章,我想知道你们是否可以帮助我。

现在我正在使用AngularJS,但我遇到验证问题,您可以在此链接中看到http://jsfiddle.net/ANxmv/1488/

问题是当你点击" Set"按钮,输入字段使用默认电子邮件更改,但angular不会触发验证。

但是如果你点击输入(没有删除它)并修改它,验证器就可以正常工作。

有没有办法在不操纵输入的情况下进行验证?

以下是HTML代码:

<form name="form" ng-app>
    <div class="control-group" ng-class="{true: 'error'}[submitted && form.email.$invalid]">
        <label class="control-label" for="email">Your email address</label>
        <p>Is it valid? {{form.email.$valid}} </p>
        <div class="controls">
            <input type="email" name="email" value="123@has.com" ng-model="email" required/>
                <span class="help-inline" ng-show="submitted && form.email.$error.required">Required</span>
                <span class="help-inline" ng-show="submitted && form.email.$error.email">Invalid email</span>
            </div>
        </div>
        <div>        
            <button type="submit" class="btn btn-primary btn-large" ng-click="submitted=true">Submit</button>
            <button class="btn btn-primary btn-large" onClick="set()" >Set</button>
        </div>
    </form>

和Javascript:

var set = function(){
    var $form_1 = document.forms['form'];
    $form_1.elements["email"].value = "123@default.com";
};

1 个答案:

答案 0 :(得分:0)

由于您正在直接从元素访问/更改其值,因此您无法正常工作,因此angular不知道该更改因此绑定无效而是使用$scope以便角度可以跟踪变化。

<强> HTML

<form name="form" ng-app="jsfiddle">
    <div ng-controller="MainCtrl" class="control-group" ng-class="{true: 'error'}[submitted && form.email.$invalid]">
        <p>Hello {{email}}!</p>
        <label class="control-label" for="email">Your email address</label>
        <p>Is it valid? {{form.email.$valid}} </p>
        <div class="controls">
            <input type="email" name="email" value="123@has.com" ng-model="email" required/>
            <span class="help-inline" ng-show="submitted && form.email.$error.required">Required</span>
            <span class="help-inline" ng-show="submitted && form.email.$error.email">Invalid email</span>
        </div>
        <button type="submit" class="btn btn-primary btn-large" ng-click="submitted=true">Submit</button>
        <button class="btn btn-primary btn-large" ng-click="set()" >Set</button>
    </div>
</div>
</form>

<强>的JavaScript

var app = angular.module('jsfiddle', []);

app.controller('MainCtrl', function($scope) {
  $scope.name = 'World';
  $scope.set = function(){
    $scope.email = "123@default.com";
  };
});

JSFiddle link