Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to call a function when input is cleared in AngularJS?

I know Angular has simple syntax to display messages or update css, but what I'm trying to do is actually call a function.

<input ng-model="somefield">
<span ng-show="!somefield.length">Please enter something!</span>
<span ng-show="somefield.length">Good boy!</span>

This is my model vm.tagSearching = '' I can detect when I start typing in the input and see the value update. However once I get to the last letter, and I delete that I don't get an update.

I tried using $scope.watch

$scope.$watch('vm.tagSearching', function() {
   alert('hey, var has changed!');
});

However this only fires once as the app initializes, but never again, even while typing.

Markup

<input class="tag-search-input"
       type="text"
       placeholder="Search Tags"
       ng-model="tgs.tagSearching"
       typeahead="t for t in tgs.fuzzyTagSearch($viewValue)">

Controller

function fuzzyTagSearch(word) {
    console.log('fuzzyTagSearch',word);
    if (word.length > 2) {
        ApiFactory.getSearchResults(word).then(function(data) {
            console.log('data',data.data.ticker_tags);
            vm.terms = data.data.ticker_tags;
        });
    }
}

How would you accomplish this? I need to detect when the input is clear when the user backspaces / deletes all the letters so that I can reset the table.

like image 779
Leon Gaban Avatar asked Mar 13 '23 10:03

Leon Gaban


1 Answers

You can simply set up an ng-change directive.

<input ng-model="tgs.tagSearching" ng-change="tgs.detectEmpty()">

vm.detectEmpty = function() {
    if (vm.tagSearching.trim().length === 0) {
        // it's empty
    }
}
like image 138
Phil Avatar answered Mar 23 '23 15:03

Phil