简体   繁体   English

AngularJS不断观察文本输入

[英]AngularJS constantly watch on text input

I am wondering if it is posible to constantly watching the text input, like typing a string and then run a function. 我想知道是否可以持续观看文本输入,比如键入一个字符串然后运行一个函数。

I would use it for html game, that if you like type the word pause on a random moment you pause the game. 我会将它用于html游戏,如果你喜欢在随机的时刻键入单词pause,你就可以暂停游戏。

Is this possible to make? 这有可能吗? or are there any easy sample scripts? 或者有简单的示例脚本吗? That would help me alot! 那会对我有所帮助! Thanks! 谢谢!

Let's say you have an input with an ng-model="myTextParam" on it. 假设您输入了一个ng-model="myTextParam" You can write in your controller the following: 您可以在控制器中写入以下内容:

$scope.$watch(function() { return $scope.myTextParam; }, function (newVal, oldVal) {
    if (newVal === "string test") {
       //do whatever
    }
});

Fiddle 小提琴

You can use $scope.$watch() to run a specific function each time a scope variable changes. 每次范围变量更改时,您都可以使用$ scope。$ watch()来运行特定的函数。 You can then check if your string is equal to 'pause'. 然后,您可以检查您的字符串是否等于“暂停”。

$scope.$watch('typeModel', function(newVal, oldVal){
    if(newVal.toLowerCase() === 'pause'){
        alert('Pause!');
    }
});  

Fiddle: http://jsfiddle.net/U3pVM/13834/ 小提琴: http//jsfiddle.net/U3pVM/13834/

Update You can use tricks to hide your input, and making sure it doesn't lose focus. 更新您可以使用技巧隐藏输入,并确保它不会失去焦点。

This css makes sure your html body takes up all the available space: 这个css确保你的html体占用了所有可用空间:

html,body {
    width: 100%;
    height: 100%;
}

You can register a clickhandler on the body to make sure you always have focus on the input: 您可以在正文上注册一个clickhandler,以确保您始终关注输入:

document.body.onclick = function(event){        
    document.getElementById('input_field').focus();
}

The autofocus part makes sure the input field gets focus on page load: autofocus部分确保输入字段专注于页面加载:

<input id="input_field" type="text" ng-model="typeModel" autofocus>

And you can do some css trick to hide your input (not the best example here, but just for demonstration purposes): 你可以做一些css技巧来隐藏你的输入(这里不是最好的例子,但仅用于演示目的):

input {
    opacity: 0.01;
}

Updated fiddle: http://jsfiddle.net/U3pVM/13847/ 更新小提琴: http//jsfiddle.net/U3pVM/13847/

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

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