在 ng-model 上输入特定字符串时触发的事件
fired event when expecific strings are being typed on a ng-model
假设当用户键入输入时 ng-model 正在更新,或者 div contenteditable,如果我们想在每次用户键入某些字符串时触发一个事件,比如“我正在写东西” ' 然后用户输入 "something" 我想触发一个事件。
无需使用手表即可解决此问题的最佳方法是什么?
根据评论中的内容,您可以执行以下操作:
var myApp = angular.module('myApp', []);
function MyCtrl($scope) {
$scope.error = false;
$scope.changed = function(input) {
$scope.error = input == 'foo' ? true : false;
}
}
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>
<div ng-app="myApp" ng-controller="MyCtrl">
<p>Don't type 'foo'</p>
<input type="text" ng-change="changed(input)" ng-model="input" />
<div ng-show="error">Gezz, you shouldn't</div>
</div>
这是一个基本的大纲。正则表达式只检查几个月,因此您必须将它们全部添加。对于这样的输入字段:
<input type="text" id="dateval" ng-model="typeddate">
在您的控制器中执行此操作:
$scope.typeddate = "";
$watch('typeddate',function(newVal,oldVal) {
var re = /jan|feb|mar|apr/i ;
var res = newVal.match(re);
if(res != null) {
// you have a match so do what you need to do
}
});
假设当用户键入输入时 ng-model 正在更新,或者 div contenteditable,如果我们想在每次用户键入某些字符串时触发一个事件,比如“我正在写东西” ' 然后用户输入 "something" 我想触发一个事件。
无需使用手表即可解决此问题的最佳方法是什么?
根据评论中的内容,您可以执行以下操作:
var myApp = angular.module('myApp', []);
function MyCtrl($scope) {
$scope.error = false;
$scope.changed = function(input) {
$scope.error = input == 'foo' ? true : false;
}
}
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>
<div ng-app="myApp" ng-controller="MyCtrl">
<p>Don't type 'foo'</p>
<input type="text" ng-change="changed(input)" ng-model="input" />
<div ng-show="error">Gezz, you shouldn't</div>
</div>
这是一个基本的大纲。正则表达式只检查几个月,因此您必须将它们全部添加。对于这样的输入字段:
<input type="text" id="dateval" ng-model="typeddate">
在您的控制器中执行此操作:
$scope.typeddate = "";
$watch('typeddate',function(newVal,oldVal) {
var re = /jan|feb|mar|apr/i ;
var res = newVal.match(re);
if(res != null) {
// you have a match so do what you need to do
}
});