angular restriction to not allow spaces in text field

<input ng-model="field" ng-trim="false" ng-change="field = field.split(' ').join('')" type="text">

Update: To improve code quality you can create custom directive instead. But don't forget that your directive should prevent input not only from keyboard, but also from pasting.

<input type="text" ng-trim="false" ng-model="myValue" restrict-field="myValue">

Here is important to add ng-trim="false" attribute to disable trimming of an input.

angular
  .module('app')
  .directive('restrictField', function () {
    return {
        restrict: 'AE',
        scope: {
            restrictField: '='
        },
        link: function (scope) {
          // this will match spaces, tabs, line feeds etc
          // you can change this regex as you want
          var regex = /\s/g;

          scope.$watch('restrictField', function (newValue, oldValue) {
              if (newValue != oldValue && regex.test(newValue)) {
                scope.restrictField = newValue.replace(regex, '');
              }
          });
        }
    };
  });

If you want to achieve it without writing directive

ng-keydown="$event.keyCode != 32 ? $event:$event.preventDefault()"


The selected answer is arguably not very unobtrusive. And if you need to use it in multiple places, you'll end up with duplicated code.

I prefer to prevent the input of spaces using the following directive.

app.directive('disallowSpaces', function() {
  return {
    restrict: 'A',

    link: function($scope, $element) {
      $element.bind('input', function() {
        $(this).val($(this).val().replace(/ /g, ''));
      });
    }
  };
});

This directive can be invoked like this:

<input type="text" disallow-spaces>