Update AngularJS ng-model only on keypress enter?

All we need is an easy explanation of the problem, so here it is.

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

<input id="search_input" type="text" ng-model="filter.search_terms">

There are many other filters I use as well (checkboxes, radio, etc) and I have a $watch on filter so any changes will fire a search. The problem is that I don’t want the search to fire for the text field every time I type a letter and only want it to “save” it on the filter.search_terms only once I press enter.

Is there an easy way to do this or do I have to remove the ng-model and do an ng-click with a function that sets it on enter?

How to solve :

I know you bored from this bug, So we are here to help you! Take a deep breath and look at the explanation of your problem. We have many solutions to this problem, But we recommend you to use the first method because it is tested & true method that will 100% work for you.

Method 1

You can try adding ng-model-options="{updateOn : 'change blur'}" to your input tag. Should work.

Method 2

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

Method 3

You can achieve this behaviour by creating a directive called updateOnEnter and then adding this attribute to your HTML element.

<input id="search_input" type="text" update-on-enter ng-model="filter.search_terms">

angular.module('app').directive('updateOnEnter', function() {
    return {
        restrict: 'A',
        require: 'ngModel',
        link: function(scope, element, attrs, ctrl) {
            element.on("keyup", function(ev) {
                if (ev.keyCode == 13) {
                    ctrl.$commitViewValue();
                    scope.$apply(ctrl.$setTouched);
                }
            });
        }
    }
});

Note: Use and implement method 1 because this method fully tested our system.
Thank you 🙂

All methods was sourced from stackoverflow.com or stackexchange.com, is licensed under cc by-sa 2.5, cc by-sa 3.0 and cc by-sa 4.0

Leave a Reply