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
Ionic fire event on input text value changes
提问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 有两种观察变化的一般方式:
- Use
$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 $watchGroup
and $watchCollection
为了完整起见,还有$watchGroup
和$watchCollection
- Using
ng-change
directive togher withng-model
:
- 使用
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-model
attribute and use ng-change
instead of ng-text-change
.
您需要添加一个ng-model
属性并使用ng-change
而不是ng-text-change
.
ng-change
is 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 = ''