2016-03-11 143 views
2

这是一个textarea元素触发按钮

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

这是一个按钮

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

我可以触发上面的按钮来提醒textarea的值使用jquery

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

有没有一种方法可以使用角度触发按钮警报默认情况下,每当一个文本或价值进入textarea的 我想用这样的

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

但沿线莫名其妙丢失。

+0

的可能的复制[如何获得与NG-变化的字段的值(http://stackoverflow.com/questions/30947808/how-to-get-the-value-of-一个字段与ng-change) – fodma1

回答

2

您可以使用内置的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> 
+0

这将触发一个特定的ID按钮 – Blaze

+0

@JNG因为它现在没有。但是在show函数中,你可以用'document.querySelector(“.btn”)手动点击按钮,点击();' – eltonkamami

+0

如果需要,请更新你的答案并显示演示。谢谢 – Blaze

0

NG-变化将帮助:

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

在控制器:

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

我希望触发按钮不要看变化 – Blaze