javascript - How prevent angular auto trim for fields? -
is there way prevent angular auto trim fields in whole application? know can prevent specified field using ngtrim directive, doesn't add directive text fields in application, there way fields in angular module? here code, if add add spaces in begin of input not appear in label:
<div ng-app> <div ng-controller="todoctrl"> {{field}} <input type="text" ng-model="field"> </div> </div>
you can extend input[text] directive, code below automatically change value of attribute ngtrim
false
:
.directive('input', function($compile){ // runs during compile return { link(scope, ielement, iattrs) { if (ielement.attr('type') === 'text') { iattrs.$set('ngtrim', "false"); } } }; });
reference: https://docs.angularjs.org/api/ng/type/$compile.directive.attributes
<!doctype html> <html lang="en"> <head> <meta charset="utf-8"> <title>example - example-text-input-directive</title> <script src="https://docs.angularjs.org/angular.min.js"></script> </head> <body ng-app="textinputexample"> <script> angular.module('textinputexample', []) .controller('examplecontroller', ['$scope', function($scope) { $scope.example = { text: 'guest' }; }]) .directive('input', function($compile){ // runs during compile return { link(scope, ielement, iattrs) { if (ielement.attr('type') === 'text') { iattrs.$set('ngtrim', "false"); } } }; }); </script> <form name="myform" ng-controller="examplecontroller"> <label>single word: <input type="text" name="input" ng-model="example.text" required> </label> <div role="alert"> <span class="error" ng-show="myform.input.$error.required"> required!</span> <span class="error" ng-show="myform.input.$error.pattern"> single word only!</span> </div> <tt>text = {{example.text}} - 3</tt><br/> <tt>text = {{example.text.length}} - 3</tt><br/> <tt>myform.input.$valid = {{myform.input.$valid}}</tt><br/> <tt>myform.input.$error = {{myform.input.$error}}</tt><br/> <tt>myform.$valid = {{myform.$valid}}</tt><br/> <tt>myform.$error.required = {{!!myform.$error.required}}</tt><br/> </form> </body> </html>
edit:
how works
1) can bind multiple directives same html element , can share same $scope
, $attributes
.
2) iattrs.$set('ngtrim', "false");
updating attribute ng-trim
. can't using normal dom manipulation because dom compiled (https://docs.angularjs.org/api/ng/service/$compile)
3) calling iattrs.$set
trigger updates on directives, override original ng-trim
attribute value.
Comments
Post a Comment