Angular ng-pattern会导致绑定中断

Angular ng-pattern causes binding to break

本文关键字:绑定 中断 ng-pattern Angular      更新时间:2023-09-26

我有一个表单:

<div class="panel-group">
    <label for="url" tooltip="Enter the Engine as a Web Service (EWS) URL the Empower Editor will use for PDF preview.">EWS URL</label>
    <input id="url" size="50" ng-model="config.ewsUrl" required ><br/>
    <label for="PreviewTimeout" tooltip="Specify how long the Empower Editor will wait for a response from the PDF preview.">Preview timeout (Seconds)</label>
    <input id="PreviewTimeout" type="number" min="15" max="60" required ng-model="config.previewTimeout" style="width: 150px;">
</div>

当我在输入中添加一个ng-pattern属性时,它会破坏绑定:

<div class="panel-group">
    <label for="url" tooltip="Enter the Engine as a Web Service (EWS) URL the Empower Editor will use for PDF preview.">EWS URL</label>
    <input ng-pattern="/^((ht|f)tp(s?)'':''/''/)?[0-9a-zA-Z]([-.''w]*[0-9a-zA-Z])*(:(0-9)*)*(''/?)([a-zA-Z0-9''-''.''?'','':'''''/''''''+=&amp;%''$#_]*)?$/" id="url" type="url" size="50" ng-model="config.ewsUrl" required><br/>
    <label for="PreviewTimeout" tooltip="Specify how long the Empower Editor will wait for a response from the PDF preview.">Preview timeout (Seconds)</label>
    <input id="PreviewTimeout" type="number" min="15" max="60" required ng-model="config.previewTimeout" style="width: 150px;">
</div>

如果我删除regex,它又回到绑定。是什么导致的呢?

看起来您正在尝试验证url。您不需要为此使用正则表达式或ng-pattern选项。只需使用以下语句:

<input type="url" id="url" type="url" size="50" ng-model="config.ewsUrl" required/>

记住,您没有得到模型绑定的真正原因可能是因为正则表达式没有验证输入的值(因为它不正确或它不是一个有效的正则表达式)。我把一个快速的柱塞器放在一起,演示有效值和无效值(在一个已验证的字段上)会发生什么。

看这里的柱塞

EDIT - Version Using ng-pattern

如果旧的浏览器支持很重要,您可能仍然需要使用ng-pattern。为了做到这一点,您需要确保正则表达式的格式是正确的(前导和尾斜杠,但没有"g")。例如,我从这里提取了url的正则表达式,并在以下代码中实现了它:

  <input id="url" type="url" size="50" ng-model="config.workingUrl2"
    ng-pattern="/https?:'/'/(www'.)?[-a-zA-Z0-9@:%._'+~#=]{2,256}'.[a-z]{2,4}'b([-a-zA-Z0-9@:%_'+.~#?&//=]*)/"
    required/>

看到这在更新的柱塞工作!祝你好运!