4

I have created an application using angularjs and ngTable with filer feature, the application is working fine also the filtering, but the filtering text-field should accept only 10 characters according to my requirement

enter image description here

Can anyone please tell me how to limit the character to 10 for that text-field, my code is as given below:

JSFiddle

script

$scope.tableParams = new ngTableParams({
    page: 0, 
    count: 0
}, {
    total: 0, 
    counts:[],
    getData: function ($defer, params) {
        // use build-in angular filter
        var orderedData = params.filter() ? $filter('filter')(data, params.filter()) : data;

        $defer.resolve(orderedData);
    }
});

html

<div ng-app="main" ng-controller="DemoCtrl">
    <table ng-table="tableParams" show-filter="true" class="table">
        <tr ng-repeat="user in $data">
            <td data-title="'Name'" filter="{ 'name': 'text' }">{{user.name}}</td>
            <td data-title="'Age'">{{user.age}}</td>
        </tr>
    </table>
</div>
Alex Man
  • 4,746
  • 17
  • 93
  • 178

1 Answers1

4

You can't do that easily with the directives provided by ng-table. In order to achieve that, you must create your own input filterer, apply it on the ng-repeat and use a simple directive which will limit the caracteres of the input field.

Here is a working example, hope it will help you. fiddle

HTML:

<div ng-app="main" ng-controller="DemoCtrl">
    <table ng-table="tableParams" class="table">
        <!-- first row with custom input filterer using the charLimit directive -->
        <tr>
            <td data-title="'Name'"><input char-limit="10" ng-model="textFilter"/></td>
            <td data-title="'Age'"></td>
        </tr>
        <!-- declare the filter on your ng-repeat directive -->
        <tr ng-repeat="user in $data | filter: { 'name': textFilter }">
            <td>{{user.name}}</td>
            <td>{{user.age}}</td>
        </tr>
    </table>
</div>

DIRECTIVE:

directive('charLimit', function(){
    return {
        scope: {
            limit: '@charLimit',
            model: '=ngModel'
        },
        require: 'ngModel',
        restrict: 'A',
        link: function($scope, $node) {
            var limit = $scope.limit ? parseInt($scope.limit, 10) : 0;
            $scope.$watch('model', function(val) {
                if(limit>0 && !isNaN(limit))
                    $scope.model = $scope.model.slice(0,limit);                        
            });
        }
    };
})

EDIT

An html5 attribute called maxlength can do it for you so you can avoid the directive and simply add this attribute to your input field

Polochon
  • 2,199
  • 13
  • 13