【问题标题】:Angular validation in form field directive doesn't work表单字段指令中的角度验证不起作用
【发布时间】:2015-05-27 11:58:36
【问题描述】:

验证在我的 formRow 指令中不起作用。我在指令中放置了一个带有字段名称的 ng-form,但不会触发 [[ field ]].$invalid 例如。有人知道为什么吗?

指令:

<li class="form__row" ng-form="[[ field ]]">
<div class="label">
    <label ng-class="{ 'required' : required == 'true' }" for="frm-[[ field ]]">[[ label ]]</label>
</div>
<div class="field" ng-switch="required" ng-class="{ 'field--invalid' : [[ field ]].$touched && [[ field ]].$invalid, 'field--valid': [[ field ]].$touched && [[ field ]].$valid }">
    <input ng-switch-when="true" type="[[ type ]]" name="[[ field ]]" id="frm-[[ field ]]" ng-model="record[ field ]" required>
    <input ng-switch-default type="[[ type ]]" name="[[ field ]]" id="frm-[[ field ]]" ng-model="record[ field ]" >
</div>

Directive.js

.directive('formRow', function () {
return {
    restrict: 'EA',
    templateUrl: FW.Config.submap + 'angular/_directives/formRow.html',
    replace: true,
    scope: {
        record: '=',
        type: '@',
        field: '@',
        label: '@',
        required: '@'
    },
    link: function($scope, element, attr) {
        // Wordt gezet bij form submit
        $scope.$on('record:invalid', function() {
            $scope[$scope.field].$setTouched;
        });
    }
}
})

从模板调用:

<form name="formData" ng-submit="submit($event)" class="form--wide frm-login" novalidate>
    <ul>
        <form-row record="inloggen" field="emailadres" label="E-mailadres" type="email" required="true"></form-row>
        <form-row record="inloggen" field="wachtwoord" label="Wachtwoord" type="password" required="true"></form-row>
    </ul>

顺便说一句:我使用方括号作为 $interpolateProvider 符号,因为在我的模板中也使用了 twig。

【问题讨论】:

    标签: angularjs validation angularjs-directive


    【解决方案1】:

    我不确定创建这样的指令是不是一个好主意,但主要问题和让它非常尴尬的是你使用了与相应元素同名的嵌套表单指令ngForm。它加起来就是范围级别。

    您可以使ngClass 与此表达式正常工作(我警告过这看起来很奇怪:):

    ng-class="{ 'field--invalid' : this[field][field].$touched && this[field][field].$invalid, 'field--valid': this[field][field].$touched && this[field][field].$valid }"
    

    首先请注意,您不要在表达式内使用插值标记,因此您不需要在 ngClass 内使用 [[ ]]。然后为了通过变量名解析动态对象属性,您将使用括号表示法,因此

    this[field][field] 
    

    这里有:

    • this 指向当前作用域对象
    • this[field] 指向 ngForm 对象,该对象与 field 中为输入元素和父元素 ngForm 定义的名称相同
    • this[field][field] 指向this[field] 访问的表单中的单个输入元素。

    演示: http://plnkr.co/edit/zarnKqPnYw4BNQQKVy9t?p=info

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2018-08-18
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2022-01-09
      相关资源
      最近更新 更多