How to $setdirty to a single input

Jhony  Blaze picture Jhony Blaze · Apr 15, 2015 · Viewed 20.7k times · Source

I've got a little problem. I want to set to dirty a single input, I mean, because when I give a value automatically it stays in pristine class, doesn't change, and doesn't save the new value.

If I edit it, it works and change the class. I want to cancel that pristine class. If anyone know please let me know.

<form class="form-horizontal" ng-repeat="studiant in studiants" name="form" id="form">

  <input type="hidden" name="id" value="{{studiant.studiant_id}}" class="form-control" disabled>

  <div class="form-group">
    <label for="school" class="col-md-2 control-label">School</label>
    <div class="col-md-1">
      <input type="text" id="school" name="school" class="form-control" ng-init="studiant.school=studiant.studiant_school" ng-model="studiant.school">
    </div>
  </div>
  <div class="form-group">
    <label for="name" class="col-md-2 control-label">Student's Name</label>
    <div class="col-md-10">
      <input type="text" id="name" name="name" class="form-control" ng-init="studiant.name=studiant.studiant_name" ng-model="studiant.name">
    </div>
  </div>
</form>

And the script:

document.getElementbyId('name').value = "anything";

Or, if I doing wrong and I have to change the value with ng-model or something, please help me.

Answer

tpie picture tpie · Apr 15, 2015

http://plnkr.co/edit/bVoljJqiK3CLB2xqZ6Zm?p=preview

You can see a working example there.

Make sure you have the name attr set for the form and the input.

HTML Example:

<button id="dirty-button" ng-click="addText(); myForm.myText.$setDirty()">Make Dirty</button>
<hr> 
<form name="myForm">   
<input name="myText" id="myTextInput" type="text" ng-model="myText" required>
</form>
<br/>
<span ng-show="myForm.myText.$dirty">it's dirty now</span>

A simple function:

$scope.addText = function() {
  $scope.myText = "now I'm dirty";
}