Update AngularJS ng-model only on keypress enter?

前端 未结 3 938
梦谈多话
梦谈多话 2021-02-13 00:44

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


There are man

3条回答
  •  眼角桃花
    2021-02-13 01:22

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

    
    
    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);
                    }
                });
            }
        }
    });
    

提交回复
热议问题