【问题标题】:Angular JS form validation in "myApp" application.“myApp”应用程序中的 Angular JS 表单验证。
【发布时间】:2017-09-22 17:30:38
【问题描述】:

我是 AngularJS 的新手,并尝试在“myApp”应用程序中实现表单验证。 我写了下面的代码。 {{result}} 应该输出“true”/“false”。但它没有用。

<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>
<body ng-app="myApp" ng-controller="myCtrl">
	<form name = "myForm">
    	<p>Input the field: </p>
        <input type = "text" name="myInput" ng-model = "myInput" required>
     </form>
        <p> The result:</p>
        <p>{{result}}</p>
        
    <script>
    	var app = angular.module("myApp", []);
        app.controller("myCtrl", function($scope){
			$scope.result = myForm.myInput.$valid;
		});
    </script>
</body>

【问题讨论】:

  • 你的问题是什么?
  • 您使用的是非常旧的 AngularJs 版本。我至少会升级到最新的稳定版本,因为任何响应都可能不兼容。

标签: javascript angularjs angularjs-scope angularjs-validation


【解决方案1】:

对于您的问题,这必须是正确的代码。 如果您“观察”“输入字段”中的变化,则会生成 $valid 结果。

<html>
<head>
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>
</head>
<body ng-app="myApp" ng-controller="MyController"> 
            <form name='myForm' novalidate>
            <p>Input the field: </p>
             <input type='text' ng-model='model.name' name='myInput' required/> 
            </form>
            <p> The result:</p>
            <p>{{myForm.myInput.$valid}}</p>
    <script> 
        var app = angular.module('myApp', []);
            app.controller('MyController',['$scope',function($scope) {
                $scope.$watch('myForm.myInput.$valid',function(newValue,oldvalue) {
                if(newValue) { 
                    //do anything with new value
                }
            });
        }]); 
    </script>
</body>
</html>

希望这对你有帮助。

【讨论】:

  • 我明白了,谢谢
【解决方案2】:

作为 angularJS 的新用户,您的方法在表单验证方面有些正确。将来您将学习 Angular 和几种验证方法的新版本。 以下代码行是我们如何在 angularJS 中检查有效输入的方式。

<!DOCTYPE html>
<html>
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.6.4/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>

你的方法是正确的。坚持下去,如果你能清楚地定义正确的问题,那就太好了。 :) 干杯。

【讨论】:

  • 谢谢。我还在我正在那里学习的 W3 学校看到了您提供的代码。我的代码基于那里进行了一些更改。基本上,我想根据我的控制器来表达验证结果。 (例如 app.controller("myCtrl", function($scope){ $scope.result = myForm.myInput.$valid;) 你能指出我的代码出错的地方吗?谢谢
  • 在编译和测试您的代码后,对我之前的答案进行了更正。希望这会有所帮助。我认为没有“监视”功能控制器将不会收到任何响应信号,除非您使用 $dirty、ng-change 等。
猜你喜欢
  • 1970-01-01
  • 2014-07-15
  • 1970-01-01
  • 1970-01-01
  • 2017-09-04
  • 2016-09-06
  • 1970-01-01
  • 2013-08-19
  • 1970-01-01
相关资源
最近更新 更多