4

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.

Community
  • 1
  • 1
Leon Gaban
  • 36,509
  • 115
  • 332
  • 529
  • Seems your `fuzzyTagSearch` doesn't return anything – Phil Feb 02 '16 at 00:25
  • I actually found a work around, sorta kinda, but not really hacky `word.length < 2` then I can call a function that way. However I'm still wondering if there is a better/more Angular way to accomplish clear input detection. – Leon Gaban Feb 02 '16 at 00:26

1 Answers1

7

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
    }
}
Phil
  • 157,677
  • 23
  • 242
  • 245