简体   繁体   中英

how to filter input value in AngularJS

I'm trying to implement filtering on my input element. I want to make filtering for input with type="text" field. For instance, if the model contain more than available characters than I want to change my input value. I've created jsfiddle I have directive that generate html template dynamically and it contains input field.

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" />'
    }
})

Could it possibly to move my code into the filter function? I have a lot of business logic and I don't want to keep my code in the controller, because it will be reusable directive.

I think that implementing this part of functionality as a filter is not the best idea.

It would be much more dynamic if you will implement it as directive on your input element like:

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

In this case it would be more flexible. You will be able to pass an argument into directive (for example length of acceptable value).

Also it is not really readable for another developers to make your input as a template of your directive because of you are using model as attribute of input field and not binding it from directive.

Is there any reason why you use directive to render simple input? If not, then just live it as input in your view and add directive instead of filter to work with data checks limitations.


Another approach is to implement custom form controls. That will allows you to control incoming and out-coming data.

Here is a example from documentation - Implementing custom form controls (using ngModel)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM