在angularjs中的模型上添加侦听器 [英] Adding a listener on a model in angularjs

查看:71
本文介绍了在angularjs中的模型上添加侦听器的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我目前有一个模型,它是搜索框的值.搜索操作执行得很好,但是我还希望在修改搜索文本时执行另一项功能.所以我想添加一个listenerwatch模型变量.我该怎么做?

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屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆