只要在textarea

时间:2016-03-11 10:49:33

标签: javascript jquery angularjs

这是一个textarea元素

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

这是一个按钮

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

我可以触发上面的按钮,使用jquery

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

当文本或值进入textarea时,默认情况下我可以使用angular来触发按钮警报 我想尝试使用这样的东西

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

但不知何故失去了一线。

2 个答案:

答案 0 :(得分:2)

您可以使用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>

答案 1 :(得分:0)

ng-change将有所帮助:

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

在控制器中:

$scope.change = function() {
    alert($scope.text);
};
相关问题