user6731422 user6731422 - 3 months ago 48
AngularJS Question

disable a textarea with angularjs

I am trying to disable a textarea from handling a keyboard event when ever a user presses the enter key of the keyboard when the textarea is empty using angularjs. I have been able to disable the submit button when the textarea is empty but I am trying to disable the textarea when from enter event when the textarea is empty.

This is my attempt:

<div class="descriptionarea">
<textarea ng-model="trackTxt" id="input" ></textarea>
<span class="buttonfortxtarea">
<button ng-disabled="!trackTxt" class= "btn btn-mini description_submit" id="new-chat-button">Submit</button></span>
</div>


When I hit enter from my textarea it triggers event using the following code

document.getElementById('input').addEventListener('keyup', function (e) {
var code = (e.keyCode ? e.keyCode : e.which);
if (code == 13) { // enter key press
send();
}
});


The above code works whether the textarea is empty or not.

EDITTED:

In my app.js of angularjs

app.controller('TodoCtrl',function($scope){

//handle javascript enter event on key up
// function TodoCtrl($scope) {

$scope.trackTxt;
$scope.send = function($event){
alert('TEST');
}

$scope.isEmpty = function(param){
return param.trim().length === 0;
}
//}

});


In jsp file

<div ng-controller="TodoCtrl">
<textarea ng-keyup="$event.keyCode == 13 && !isEmpty(trackTxt) && send($event)" ng-model="trackTxt" id="input" ></textarea>
<span class="buttonfortxtarea">
<button ng-disabled="!trackTxt" ng-click="send($event)" class= "btn btn-mini description_submit" id="new-chat-button">Submit</button></span>
</div></div>


Please how can I use angularjs to prevent the enter event from happening when ever the text-area is empty.

Answer

You can use ng-keyup for attaching an function on enter key press,

ng-keyup="$event.keyCode == 13 && functionToCall()"

Here is demo,

Thanks