有没有办法防止整个应用程序中字段的角度自动修剪?我知道我可以使用 ngTrim 指令防止指定字段出现这种情况,但将此指令添加到应用程序中的所有文本字段看起来不太好,有什么方法可以对 Angular 模块中的所有字段执行此操作吗? 这是代码,如果您在输入的开头添加空格,它们将不会出现在标签中:
<div ng-app>
<div ng-controller="TodoCtrl">
{{field}}
<input type="text" ng-model="field">
</div>
</div>
您可以扩展 input[text] 指令,下面的代码会自动将属性
ngTrim
的值更改为 false
:
.directive('input', function($compile){
// Runs during compile
return {
link(scope, iElement, iAttrs) {
if (iElement.attr('type') === 'text') {
iAttrs.$set('ngTrim', "false");
}
}
};
});
参考: 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>
如何运作
$scope
和 $attributes
。iAttrs.$set('ngTrim', "false");
正在更新属性 ng-trim
。你不能使用普通的 dom 操作来做到这一点,因为 dom 已经编译了(https://docs.angularjs.org/api/ng/service/$compile)iAttrs.$set
将触发所有指令的更新,因此它将覆盖原始 ng-trim
属性值。扩展
input
指令(或任何指令/服务)的另一种方法是使用 decorator:
app.config(function($provide) {
$provide.decorator('inputDirective', function($delegate) {
var directive = $delegate[0],
link = directive.link;
link.post = function(scope, element, attrs) {
attrs.$set('ngTrim', 'false');
};
return $delegate;
});
});
我个人更喜欢这种方法,因为它允许我在需要时执行指令的原始代码。在这种特殊情况下,这是不必要的,因为
input
指令没有链接功能,因此您可以简单地提供自己的链接功能,而不必担心破坏任何内容。