javascript 输入文本值更改时的离子触发事件

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/31836174/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-28 14:25:45  来源:igfitidea点击:

Ionic fire event on input text value changes

javascriptangularjsionic-frameworkionic

提问by user2877989

In Ionic, how can you catch an event on a text input field when its value changes?

在 Ionic 中,当文本输入字段的值发生变化时,如何在其上捕获事件?

The input field:

输入字段:

<input type="search" placeholder="Search" ng-text-change="searchMenu()">

The controller:

控制器:

// ...
    $scope.searchMenu = function () {
        alert('changed')
        console.log(1);
    };
// ...

Nothing happens when typing into the text field.

在文本字段中输入时没有任何反应。

回答by vittore

Ionic is Angular in a nutshell, and angular has two general ways of watching for changes:

简而言之,Ionic 就是 Angular,而 Angular 有两种观察变化的一般方式:

  1. Use $scope.$watch:
  1. 使用$scope.$watch

markup:

标记:

 <input type="search" placeholder="Search" ng-model="search" />

and code:

和代码:

  $scope.$watch('search',function (oldValue, newValue) {
     alert('changed')
     console.log(1)
  });

For the sake of completeness there are also $watchGroupand $watchCollection

为了完整起见,还有$watchGroup$watchCollection

  1. Using ng-changedirective togher with ng-model:
  1. 使用ng-change指令togher有ng-model

markup:

标记:

 <input type="search" placeholder="Search" 
        ng-model="search" 
        ng-change="onSearchChange()" />

and code:

和代码:

 $scope.onSearchChange = function () {
    alert('changed')
    console.log(1)
}

There are also advanced ways of getting changes, like creating directive that is talking to ngModel directive controller and/or creating custom formatter and parser to work with ng-model.

还有一些获得更改的高级方法,例如创建与 ngModel 指令控制器对话的指令和/或创建自定义格式化程序和解析器以使用 ng-model。

回答by mhx

You need to add an ng-modelattribute and use ng-changeinstead of ng-text-change.

您需要添加一个ng-model属性并使用ng-change而不是ng-text-change.

ng-changeis a built-in angular directive which fires events when the binded model (ng-model) changes. ngChange documenation

ng-change是一个内置的 angular 指令,它在绑定模型 ( ng-model) 更改时触发事件。ngChange 文档

So your html would be like:

所以你的 html 会是这样的:

<input ng-model="inputValue" ng-change="searchMenu" type="search" placeholder="Search">

In your controller, you need to add a $scope variable like:

在您的控制器中,您需要添加一个 $scope 变量,例如:

$scope.inputValue = ''

$scope.inputValue = ''

回答by Medet Tleukabiluly

It's ng-changenot ng-text-changeand you must have ng-modelon that input element to trigger ng-change event

它是ng-change不是ng-text-change,你必须在那个输入元素上有ng-model才能触发 ng-change 事件

docs

文档