dman dman - 1 month ago 15
AngularJS Question

Angular.js required and ng-required not working for <textarea></textarea>

I can not get Angular.js

required
or
ng-required
to work. I want it to where if the user hits ok, they have to have some text in the textbox.

<div class="modal-body">
<p>Your change will be logged. Please provide a ticket number or comment for reference</p>
<div class="row">
<div class="span4">
<textarea type="text" class="form-control"
ng-model="commentBox.text"
ng-required="commentBox.text">
</textarea>
</div>
</div>
</div>


Scratching my head.....

Answer

two things:

  1. make sure that value you are passing to ng-required is boolean (to be technically correct, it should evaluate to boolean)

     <textarea type="text" class="form-control" 
        ng-model="commentBox.text" 
        ng-required="commentBox.textRequired">
    </textarea>
    
    //somewhere in your controller
    $scope.commentBox.textRequired = true
    
  2. you would need form.$invalid on your button

    <button type="submit" ng-disabled="formname.$invalid" ng-click="onsubmit()"></button>
    

so to complete it

   <ng-form name="exampleForm">
     <textarea type="text" ng-model="commentBox.text" ng-required="true"></textarea>
     <button ng-disabled="exampleForm.$invalid" ng-click="onsubmit()"></button>
   </ng-form>