<!doctype html> <html> <head> <title>Add remove required validation in angular dynamically in angular js</title> <script src="http://code.angularjs.org/1.2.12/angular.js"></script> <script src="http://code.jquery.com/jquery-2.1.1.min.js"></script> </head> <body> <div data-ng-app="myApp" data-ng-controller="MyController"> <form name="myForm" method="get" validate-form novalidate> <div class="container"> Type: <select ng-model="type" my-validation> <option value="required">Required</option> <option value="not_required">Not Required</option> </select> </div> <div class="container"> Name: <input type="text" name="name" ng-model="name" ng-required="isFieldRequired()" my-validation/> <span ng-show="myForm.name.$invalid" style="color:red;font-size:30px;">*</span> </div> <div><input type="submit" value="Submit"/></div> </form> </div> <script type="text/javascript"> var app = angular.module("myApp", []); app.controller("MyController", function($scope) { $scope.type = "required"; $scope.isFieldRequired = function() { return $scope.type == "required"; } }); app.directive('validateForm', function () { return { restrict: 'A', link: function ($scope, form) { form.on('submit', function () { $(form).find(".container").css("border", ""); if($scope.myForm.$invalid) { var error = $scope.myForm.$error; for (var key in $scope.myForm.$error) { for (var index = 0; index < $scope.myForm.$error[key].length; index++) { var err = $scope.myForm.$error[key][index]; console.log("Field=" + err.$name + ', Error=' + key); } } var firstInvalid = $(form[0].querySelector('.ng-invalid')); if (firstInvalid.length > 0) { firstInvalid.closest(".container").addClass("error_element").css("border", "2px solid red"); firstInvalid.focus(); return; } } console.log("Form Validated"); }); } }; }); app.directive("myValidation", function() { return { restrict: "A", require: "ngModel", link: function(scope, elem, attrs, ctrl) { console.log(attrs) } } }) </script> </body> </html>
Tuesday, December 13, 2016
Add remove required validation in angular dynamically in angular js
Subscribe to:
Post Comments (Atom)
Thanks for sharing, it is very usefull information
ReplyDeleteAngular JS Online training
Angular JS training in hyderabad