简体   繁体   English

如何在AngularJS中清除输入时调用函数?

[英]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. 我知道Angular有简单的语法来显示消息或更新css,但我想要做的是实际上调用一个函数。

<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. 这是我的模型vm.tagSearching = ''当我开始输入输入并看到值更新时,我可以检测到。 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

$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. 当用户退格/删除所有字母以便我可以重置表格时,我需要检测输入何时清除。

You can simply set up an ng-change directive. 您只需设置ng-change指令即可。

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

vm.detectEmpty = function() {
    if (vm.tagSearching.trim().length === 0) {
        // it's empty
    }
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM