在angularjs中的模型上添加侦听器 [英] Adding a listener on a model in angularjs
问题描述
我目前有一个模型,它是搜索框的值.搜索操作执行得很好,但是我还希望在修改搜索文本时执行另一项功能.所以我想添加一个listener
或watch
模型变量.我该怎么做?
I currently have a model which is the value of a search box. The search operation is performing perfectly but I also want yet another feature to be performed when the search text is modified. So i wanna add a listener
or watch
the model variable. How can I do it?
推荐答案
您有2个选项可以满足您的用例:
You've got 2 options to cover your use case:
使用 ng-change 指令
Use the ng-change directive
您可以这样编写输入内容:
You can write your input like so:
Search: <input ng-model="search.model" ng-change="changeHandler()">
其中changeHandler
是在作用域上定义的函数.
where the changeHandler
is a function defined on a scope.
在示波器上使用手表
通过写控制器:
$scope.$watch('search.model', function(newVal, oldVal){
console.log("Search was changed to:"+newVal);
$scope.search.watch = newVal;
});
这里有一个工作的小精灵说明了这两个问题: p =预览
Here is a working plunk illustrating both: http://plnkr.co/edit/Jgb2slcBFzLNKK0JFNyo?p=preview
两种方法之间的区别在于,ng-change
仅会因用户对输入的迭代而触发,而$watch
会针对任何模型突变(由输入控件或模型的任何其他更改触发)触发.因此,您可以精确选择要响应的事件.
The difference between the 2 approaches is that ng-change
will fire only as a result of user's iteractions with an input while $watch
will fire for any model mutation - triggered from the input control or any other change to the model. So you can preciselly choose on which events you want to react.
这篇关于在angularjs中的模型上添加侦听器的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!