2015-08-15 31 views
0

現在輸入,我有一個非常典型的過濾器的使用示例:Angularjs過濾搜索文本與驗證規則

... 
Search: <input ng-model="searchText"> 
<table> 
    <tr ng-repeat="friend in friends | filter:searchText"> 
     <td>{{friend}}</td> 
    </tr> 
</table> 
... 

直到我把一個正則表達式規則input標籤,現在碼這工作得很好:

... 
Search: <input ng-model="searchText" ng-pattern='/John|Mary|Mike|Adam/'> 
<table> 
    <tr ng-repeat="friend in friends | filter:searchText"> 
     <td>{{friend}}</td> 
    </tr> 
</table> 
... 

See this plunker

除非你通過了驗證規則,此過濾器,然後開始工作,它似乎驗證規則防止ŧ他的關鍵字被傳遞到過濾器,直到關鍵字符合正則表達式規則,我期望的是驗證只有在searchText失去焦點時纔會生效。

我現在使用的是一個非常醜陋的解決方法,就像dynamic ng-pattern,我把表達式放入參數​​3210,然後searchText更改爲<input ng-model="searchText" ng-pattern='regex' ng-focus="regex=''" ng-blur="regex = /John...../">

有沒有更好的解決方案呢?

+0

你究竟想在這裏做什麼? – Shreyas

回答

1

您應該看看ng-model-options API,該API有更新ng-model各種事件或延遲的選項。

ng-model-options="{ updateOn: 'blur' }" 

Working Plunkr

+0

是的,這個'ng-model-options'是我想要的,事實上我需要把'ng-model-options =「{allowInvalid:true}」'解決我的問題。謝謝 –

+0

@ z.Neeson很高興爲您提供幫助。謝謝 –

1

Probably you're looking for this

(從官方網站複製)

下面的例子演示如何重寫即時更新。只有當控件失去焦點時(模糊事件),表單中輸入的更改纔會更新模型。如果在輸入字段聚焦時按下了退出鍵,則該值將重置爲當前模型中的值。

<div ng-controller="ExampleController"> 
    <form name="userForm"> 
    <label>Name: 
     <input type="text" name="userName" 
      ng-model="user.name" 
      ng-model-options="{ updateOn: 'blur' }" 
      ng-keyup="cancel($event)" /> 
    </label><br /> 
    <label>Other data: 
     <input type="text" ng-model="user.data" /> 
    </label><br /> 
    </form> 
    <pre>user.name = <span ng-bind="user.name"></span></pre> 
</div>