javascriptangularjsangularjs-scopeangularjs-validation

Angular JS form validation in "myApp" application.


I am new to AngularJS and try to implement form validation in "myApp" app. I wrote the code below. The {{result}} should output "true"/"false". But it didn't work.

<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>


Solution

  • This must be correct code for your problem. If you "watch" the changes in the "input field" then $valid result will generate.

    <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>
    

    Hope this will be helpful to you.