How to $setdirty to a single input

巧了我就是萌 提交于 2019-12-10 14:42:37

问题


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.


回答1:


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";
}



回答2:


$scope.$on('$viewContentLoaded'){
 $scope.form.fieldName.$dirty = true;
 }

When your view is loaded then angular calls viewContentLoaded event is called. After that you can set the field dirty. And also if you want to call some method ,that should be executed after the content is loaded than you should call that method inside this $scope.$on('$viewContentLoaded'){..}




回答3:


This should do the job

angular.element(document.querySelector('form')).scope().formname.fieldname.$setDirty()



来源:https://stackoverflow.com/questions/29651931/how-to-setdirty-to-a-single-input

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!