角度ng模式导致绑定中断

时间:2014-07-01 15:50:35

标签: javascript angularjs

我有一张表格:

<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>

如果我删除了reg ex,它会再次回到绑定状态。什么可能导致这种情况?

1 个答案:

答案 0 :(得分:4)

看起来您正在尝试验证网址。您不需要使用正则表达式或ng-pattern选项。而只需使用以下内容:

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

考虑到这一点,你没有得到模型绑定的真正原因可能是因为正则表达式没有验证输入的值(因为它不正确或者它不是有效的正则表达式)。我整理了一个快速的plunker,演示了有效值和无效值(在经过验证的字段上)会发生什么。

<强> See the plunker here

编辑 - 使用ng-pattern的版本

如果较旧的浏览器支持很重要,您可能仍需要使用ng-pattern。为此,您需要确保正则表达式的格式正确(前导和尾随斜杠,但没有“g”)。举个例子,我为url from here提取了一个正则表达式,并在以下代码中实现了它:

  <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/>

See this working in the updated plunker祝你好运!

相关问题