简体   繁体   English

使用JavaScript弄脏AngularJS表单页面

[英]Making AngularJS form page dirty using JavaScript

I want to make the AngularJS form field dirty by using JavaScript code, 我想通过使用JavaScript代码来使AngularJS表单字段变脏,

Here is the HTML Code 这是HTML代码

 <!DOCTYPE html> <html> <script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.6.9/angular.min.js"></script> <body ng-app=""> <p>Try writing in the input field:</p> <form name="myForm"> <input name="myInput" ng-model="myInput" required> </form> <p>The input's valid state is:</p> <h1>{{myForm.myInput.$valid}}</h1> </body> </html> 

I tried using 我尝试使用

document.querySelector('input[name="myInput"]').value="123",

clicking, focusing but none of them seems to work/override it. 单击,集中注意力,但似乎没有一个起作用/可以覆盖它。 Please guide me on how to do that without using AngularJS functions and by using plain JavaScript. 请指导我如何使用AngularJS函数以及使用普通JavaScript来执行此操作。

I want to change the input's valid state to true 我想将输入的有效状态更改为true

To interact with angular App from console you need to use 要从控制台与angular App进行交互,您需要使用

var scope = angular.element(document.getElementById('yourElementId')).scope();

this will bring you the required scope, then to set element as dirty you can use 这将为您带来所需的范围,然后将元素设置为脏,您可以使用

scope.myForm.myInput.$setViewValue(scope.myForm.myInput.$viewValue);

Use: 采用:

   var $body = angular.element(document.body);
   var $scope = $body.data().$scope;
   $scope.myForm.myInput.$setDirty();
   $scope.$apply();

The DEMO 演示

 setTimeout(function() { var $body = angular.element(document.body); var $scope = $body.data().$scope; $scope.myForm.myInput.$setDirty(); $scope.$apply(); }, 1000); 
 <!DOCTYPE html> <html> <script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.6.9/angular.min.js"></script> <body ng-app=""> <p>Watch dirty state flash from false to true</p> <form name="myForm"> <input name="myInput" ng-model="myInput" required> </form> <p>The input dirty state is:</p> <h1>{{myForm.myInput.$dirty}}</h1> </body> </html> 

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM