Calling angularjs function on text input based on length

blue piranha picture blue piranha · May 15, 2015 · Viewed 40.4k times · Source

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

Answer

Shadow3188 picture Shadow3188 · May 15, 2015

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>