Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Calling angularjs function on text input based on length

I have a text box. I would like to call a method inside controller only when user has filled in 'n' or more number of characters in the textbox.

Can someone please give me pointers on how to approach this?

Thanks

like image 476
blue piranha Avatar asked May 15 '15 18:05

blue piranha


2 Answers

Id recommend just using ngChange and binding to an evaluation function. Below is a sample

angular.module('inputChange', [])
    .controller('TextInputController', ['$scope', function ($scope) {
    var inputMin = 3;
    $scope.someVal = '';
    $scope.result = '';
    $scope.textChanged = function() {
        if ($scope.someVal.length >= inputMin) executeSomething()
        else $scope.result = '';
    };

    function executeSomething() {
        $scope.result = $scope.someVal;
    };
}]);
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>
<div ng-app="inputChange" ng-controller="TextInputController">
    <input type="text" ng-model="someVal" ng-change="textChanged()" ng-Trim="false" /> 
    <br />

    someVal: <span ng-bind="someVal"></span>
    <br />
    Result: <span ng-bind="result"></span>
    <br />
    someVal Length: <span ng-bind="someVal.length"></span>
    <br />
    Result Length: <span ng-bind="result.length"></span>
</div>
like image 82
Shadow3188 Avatar answered Sep 27 '22 18:09

Shadow3188


You could simply achieve this by using ng-keyup directive

ng-keyup="(1myNgModel.length >= n) && myFunction()"

Desired function will only gets called only if length of model is greater than equal to n length

Working Plunkr


Though the better version would be having ng-model-options with debounce time, so that it will reduce number of value change. After that we can easily use ng-change directive to fire function.

<input type="text" ng-model="myNgModel" 
  ng-change="(myNgModel.length >= 3) && myFunction()" 
  ng-model-options="{ debounce: 200 }" />

Updated Demo

like image 27
Pankaj Parkar Avatar answered Sep 27 '22 18:09

Pankaj Parkar