每当在文本区域上输入按钮时,都会触发按钮

Trigger a button whenever a button is entered on a textarea

本文关键字:按钮 输入 文本 区域      更新时间:2023-09-26

这是一个文本区域元素

<textarea id="textfield" paceholder="type anything here"></textarea>

这是一个按钮

<button type="button" class="btn btn-danger" id="button">Alert</button>

我可以触发上面的按钮,使用 jquery 提醒文本区域的值

<script>
$(function() {
  $('#button').click(function() {
    var value = $('#textfield').val();
      alert(value);
  });
});
</script>

有没有办法在文本或值进入文本区域时默认使用 angular 触发按钮警报我正在尝试使用这样的东西

$scope.$watch('textfield', function () {
//pop alert if textarea has a value

但不知何故迷失了。

您可以使用 Angular 的内置ngKeyup指令

<div ng-app="myapp" ng-controller="myctrl">
  <textarea ng-keyup="show($event)" name="" id="" cols="30" rows="10"></textarea>
</div>

你的 js

angular.module("myapp",[])
.controller("myctrl", function($scope){
  $scope.show = function($event){
    alert($event.target.value);
  }
})

如果您需要在每次输入文本时强制单击按钮,请按如下方式更改show功能

angular.module("myapp",[])
.controller("myctrl", function($scope){
  $scope.show = function($event){
    alert($event.target.value);
    document.querySelector(".btn").click();
  }
})

注意:ngKeyup 每次释放该键时都会触发,如果您需要侦听在 textaread 中输入的每个字符,请使用 ngChange 事件

<div ng-app="myapp" ng-controller="myctrl">
  <textarea ng-change="show($event)" name="" id="" cols="30" rows="10"></textarea>
</div>

ng-change会有所帮助:

<input type="textbox" ng-model="text" ng-change="change()"  />

在控制器中:

$scope.change = function() {
    alert($scope.text);
};