AngularJS:验证ng-disabled / ng-readonly字段

时间:2015-09-08 07:12:58

标签: javascript angularjs forms validation

我潦草地写了this jsFiddle来描述手头的问题。基本上我有一个包含某些ng-required文本输入的表单。问题是用户无法在其中键入内容,但必须单击一个按钮,该按钮会打开一个包含允许值列表的对话框;点击一个相应地设置输入ng-model(在我的例子中,输入旁边的按钮立即设置ng-model,但你得到了jist)。
麻烦的是,如果我设置ng-disabled(可理解)或ng-readonly(老实说,我无法弄清楚为什么),即使字段留空,也会提交表单,而我想强制执行用户输入。我怎么能实现这个目标?欢呼声。

2 个答案:

答案 0 :(得分:2)

我通过添加另一个共享相同模型的输入并将其放在可见模型下方来解决这个问题。但是你不能只是做一个隐藏的输入(通过设置type =" hidden"或ng-hide等等),因为隐藏它完全不会让验证显示出来。 / p>

<!-- Normal input: we want this to be required, yet read-only -->    
<input id="inputMyValue" ng-model="myValue" ng-click="openSelectionDialog()" ng-readonly="true"/>

<!-- Hidden input: not really hidden - just visible enough for the validation to work -->
<input id="inputMyValueHidden" ng-model="myValue" ng-required="true"  style="height: 0; border: 0;"/>

答案 1 :(得分:1)

在提交时编写自己的验证功能:

$scope.validateForm = function() {
    if ($scope.myDisabledInput === '') {
        return;
    }
};

我会以某种方式提醒用户,但这至少应该指向正确的方向。