简体   繁体   中英

Angular ng-pattern causes binding to break

I've got a form:

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

When I add an ng-pattern attribute to the input it breaks the binding:

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

If I remove the reg ex, it goes back to binding again. What could cause this?

It looks like you are trying to validate a url. You don't need to use a regular expression or the ng-pattern option for this. Instead just use the following:

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

That in mind, the real reason that you aren't getting model binding is probably because the regular expression is not validating the values entered (either because it is incorrect or it is not a valid regular expression). I put together a quick plunker demonstrating what happens with valid and invalid values (on a validated field).

See the plunker here .

EDIT - Version Using ng-pattern

If older browser support is important, you will probably still need to also use ng-pattern . In order to do this you need to make sure the regular expression is in the correct format (leading and trailing slash, but no "g"). For an example I pulled a regular expression for url's from here and implemented it in the following code:

  <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 ! Best of luck!

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM