2015-11-19 155 views
1

我正在嘗試創建一個typeahead指令,該指令不會在輸入時將鍵入的文本綁定到模型。ngModel上的延遲綁定

這是因爲這種沒問題,但我想用ngModel指令對我的約束力,所以我可以使用類似的東西來

<input type="text" ng-model="model.field" typeahead="sourceForTypeahead" /> 

,而不是我這可以作爲一個魅力

電流的方法
<input type="text" ng-model="tmpFieldForInput" typeahead="sourceForTypeahead" typeahead-model="model.field" /> 

是否有可能從內部改變NG-模型的「目標」的指令我想不通,所以我得到了打字輸入,然後能夠將外部模型時,從一個結果源被選中。

回答

0

在查看舊版本的複選框列表模塊後,我找到了一個解決方案。

解決方法是在編譯時更改ngModel屬性,並使其指向指令中的內部屬性,然後在後鏈接方法中進行編譯。

我已經更新了plunker給別人看的原型:http://plnkr.co/edit/LbHH2pJGX1Iii8ZqqSie?p=preview

(堆棧需要我張貼的代碼 - 所以這裏是)

app.directive('typeahead', ['$parse', '$compile', function ($parse, $compile) { 
    return { 
     priority: 1000, 
     terminal: true, 
     scope: { 
      source: '=typeahead', 
      ngModel: '=' 
     }, 
     compile: function(tElement, tAttrs) { 
      tElement.removeAttr("typeahead"); 
      tElement.attr("ng-model", "searchTerm"); 

      return function(scope, element, attrs) { 
       $compile(element)(scope); 
       // all my logic here 
2

使用ngModelOptions指定當你想輸入文本到模型綁定:

<input type="text" ng-model="myModel" ng-model-options="{ updateOn: 'blur' }"> 
<p>Hello {{myModel}}!</p> 

有不同的事件可以觸發,但在這種情況下,文本將僅結合該模型一旦終端用戶將焦點從現場移開。

其他資源:https://docs.angularjs.org/api/ng/directive/ngModelOptions

+1

此外,您還可以檢查NG-模型選項=「{debounce:2000}」。這是更新模型,鍵入後延遲2秒。這個東西對typeahead很有用。 –

+0

儘管源數組包含[「Test」,「Build」],這仍然會將「tes」綁定到模型上。 也許自定義驗證是要走的路,然後阻止提交無效數據? 我最大的問題是源數組可能更復雜,例如[{「name」:「Test」,「id」:1},{「name」:「Build」,「id」:2}]因此我希望用戶選擇其中一個複數值 - 但是在這裏,我可能能夠使用setViewValue –

+0

和$ scope。$ watch(「myModel」,function(newValue,oldValue){})仍然會對「無效」modelValue作出反應:/ –

0

像@lux提到,去做正確的方法是使用ng-model-options

但在你的情況下,理想的解決辦法是做包裝你輸入的形式和綁定上提交:

<form name="myForm"> 

<input type="text" ng-model="myModel" ng-model-options="{ updateOn: 'submit' }"> 
<p>Hello {{myModel}}!</p> 
<input type="submit" value="Submit"> 
</form> 

這將值綁定到模型只有當你點擊你的提交按鈕。這當然可以放在任何你喜歡的地方。