Javascript – Calling angularjs function on text input based on length

angularjsangularjs-ng-changehtmljavascript

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

Best Solution

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>