Update AngularJS ng-model only on keypress enter?

前端 未结 3 835
日久生厌
日久生厌 2021-02-13 00:24

I have this input field I am using for a search:


There are man

3条回答
  •  长发绾君心
    2021-02-13 01:08

    Neither of the answers here seem to fully answer the question. The question was how to get the model to ONLY update on pressing enter. I'm sure the original poster has moved on, but for others who may find this, I'll add my approach. I think ninjaPixel got the closest. My response is based off of his directive.

    The missing piece however is preventing the default ng-model directive from updating in other cases. To do that, I added an option to the input to update on keyup:

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

    This overrides the default which updates on input events (for text fields) and forces the update to occur on keyup. This allows our directive to prevent the original ng-model directive's default action by stopping event propagation in our custom keyup handler:

    if (ev.keyCode !== 13) return ev.stopImmediatePropagation();
    

    A working codepen can be found here: http://codepen.io/jessehouchins/pen/MbmEgM

提交回复
热议问题