【问题标题】:Validation of a custom directive (I want to make it required) in AngularJs在 AngularJs 中验证自定义指令(我想让它成为必需的)
【发布时间】:2016-04-26 12:53:22
【问题描述】:

我在使用 AngularJS 验证表单中的自定义指令时遇到问题。我创建的指令称为 switcher,它被放入一个表单 ChoixController 表单中。

代码是这样的:

    <form id="choixContext"  name="choixContext" ng-submit="choixController.save(choixContext)">
<label for="choixDevis">Choice of Devis </label>
 <switcher name="choixDevis" id="choixDevis" grid="'grid-3-small-3-tiny-1'" values="choixContextContrat" model="codeChoix"/>
    <div class="msg-error-input"
         ng-if="!codeChoix"
         ng-messages="choixContext['codeChoix'].$error"
         role="alert">
        <div class="icon icon-mobile-attention-carre" ng-message="required">
            Erreur !
        </div>
    </div>
<button type="submit">Submit</button>
    </form>

我该怎么做?我希望该指令是必需的。用户必须在提交前选择点击指令。

这是指令的 HTML 代码:

<div class="switcher {{grid}}" ng-cloak>
    <label class="switch {{item.class}}"
         data-ng-repeat="item in values">
        <input name="{{name}}" type="radio" value="{{item.code}}" ng-model="$parent.model">
        <span class="switch-data">
            <span class="icon {{item.icon}}" data-ng-if="item.icon"></span>
            <span class="switcher-libelle" data-ng-bind-html="item.libelle"></span>
        </span>
    </label>
    <label class="switch switch-other" data-ng-if="otherRadio">
        <input id="{{otherRadioId}}" name="{{name}}" type="radio" value="{{otherRadioValue}}" ng-model="$parent.model">
        <span class="switch-data" data-ng-bind-html="otherRadioLibelle"></span>
    </label>
</div>

【问题讨论】:

  • 顺便说一句,在屏幕上显示您的客户名称可能不是一个好主意。
  • 你是对的。我编辑了我的帖子。感谢您的帮助!

标签: javascript angularjs angular-directive


【解决方案1】:

据我所知,角度形式只会将 input select textarea 添加到他的有效性系统中。

解决这个问题的一个简单方法是创建一个隐藏输入:

<input name="monChoix" type="hidden" ng-model="codeChoix" required />
 <div class="msg-error-input"
     ng-if="!codeChoix"
     ng-messages="choixContext['monChoix'].$error"
     role="alert">
    <div class="icon icon-macif-mobile-attention-carre" ng-message="required">
        Erreur !
    </div>
</div>

另请注意,在您的 ng-messages 中必须匹配的是输入名称,而不是您存储值的变量名称。这就是为什么我将其重命名为 monChoix 以便您更好地看到链接。

【讨论】:

  • 然后你必须在指令的输入中添加 required 。如果你不想修改他们的代码,你可以使用 $decorator 来改变模板。
  • 这里有一个小演示:angular-tips.com/blog/2013/09/experiment-decorating-directives。检查指令的源代码。如果模板被定义为指令的template var,您只需更改 $decorator.template 值以将所需的值添加到输入中。要了解更多信息,我们需要切换器的指令声明。
【解决方案2】:

更好的选择是使用 ng-message。接下来您需要在&lt;switcher /&gt; 上执行此操作:

  • 更改 ng-model 的模型
  • 需要添加属性

接下来,您需要添加 ng-messages:

<div ng-messages="choixContext.choixDevis.$error" role="alert">
  <div ng-message="required">You did not enter a field</div>
</div>

更多信息: https://docs.angularjs.org/api/ngMessages/directive/ngMessages

如果您需要更多帮助,请做一个 plunker。

【讨论】:

  • 我添加了指令的HTML代码..不知道对你有没有帮助
猜你喜欢
  • 2017-05-26
  • 2014-03-07
  • 2013-02-19
  • 2017-01-05
  • 2015-09-12
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2016-09-13
相关资源
最近更新 更多