在AngularJs中验证自定义指令(我想让它成为必需)

时间:2016-04-26 12:53:22

标签: javascript angularjs angular-directive

我在使用AngularJS验证表单中的自定义指令时遇到问题。我创建的指令称为切换器,它放在表单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>

2 个答案:

答案 0 :(得分:0)

据我所知,有角度的表格只会将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,以便您更好地查看链接。

答案 1 :(得分:0)

更好的选择是使用ng-message。接下来你需要在<switcher />上执行此操作:

  • 更改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

如果您需要更多帮助,请做一名傻瓜。