如何过滤 AngularJS 中的输入值

how to filter input value in AngularJS

我正在尝试对我的输入元素进行过滤。 我想使用 type="text" 字段对输入进行过滤。 例如,如果模型包含的字符多于我想要更改输入值的字符数。 我创建了 jsfiddle 我有动态生成 html 模板的指令,它包含输入字段。

var app = angular.module('app', [])

.controller('ctrlr', function($scope){
    $scope.myModel = "test";
    $scope.availableCharacters = 5;
    $scope.$watch('myModel', function(newValue, oldValue){
        if(!newValue){
            return;
        }
        if(newValue.length > 5){
             $scope.cutString();       
         }
    });
    $scope.cutString = function(){
        var length = $scope.myModel.length;
        var string = $scope.myModel.slice(0, $scope.availableCharacters);
        var countStars = length - string.length;
        $scope.myModel = $scope.createStars(string, countStars);
    }
    $scope.createStars = function(string, countStars){
        for(var i = 1; i <= countStars; i++){
                string = string+'*';
            }

        return string;
    }
})
.directive('awesome' , function(){
    return {
        restrict:'E',
        template:'<input type="text" ng-model="myModel" ng-value="myModel | filter:my" />'
    }
})

是否可以将我的代码移动到过滤器函数中?我有很多业务逻辑,我不想将我的代码保留在控制器中,因为它将是可重用的指令。

我认为将这部分功能实现为过滤器并不是最好的主意。

如果您将它作为输入元素上的指令来实现,它将更加动态,例如:

<input type="text" ng-model="myModel" ng-value="myModel" max-length="20" />

在这种情况下,它会更灵活。您将能够将参数传递给指令(例如可接受值的长度)。

对于其他开发人员来说,将您的输入作为指令的模板也不是真正可读的,因为您使用模型作为输入字段的属性,而不是将其与指令绑定。

你使用指令来呈现简单输入有什么原因吗? 如果没有,那么只需将其作为视图中的输入并添加指令而不是过滤器以处理数据检查限制。


另一种方法是实现自定义表单控件。这将允许您控制传入和传出数据。

这是文档中的示例 - Implementing custom form controls (using ngModel)