Developer_29 Developer_29 - 4 months ago 28
AngularJS Question

How to pass angularjs scope variable value as FormName to ng-click param and get FormName.$valid and FormName.$dirty view

How can I pass a scope variable as FormName of

ng-click
parameter to get
FormName.$valid
and
FormName.$dirty
in view angularjs.

Example:



var myApp = angular.module('myApp', []);
myApp.controller('Main', ['$scope',
function($scope) {
$scope.FormName = 'FormNameValidation';
$scope.showFormValidation = function(statusValid, statusDirty) {
console.log(statusValid, statusDirty);
$scope.FormNameValidationStatus = statusValid;
$scope.FormNameDirtyStatus = statusDirty;
}
}
]);

<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>
<div ng-app='myApp' ng-controller="Main">
<form name="MainFormName" novalidate>
<button type="button" ng-click="showFormValidation(FormName.$valid, FormName.$dirty)">Click</button>
<form name="FormNameValidation" novalidate>
<div class="col-sm-6">
<div class="form-group" ng-class="{ 'has-error' : FormNameValidation.type.$invalid }">
<label class="col-sm-4 red" for="form-field-1-1">Type</label>
<div class="col-sm-8" ng-class="{ 'has-error' : type.$invalid }">
<select convert-number ng-required=&#39;true&#39; class="form-control" id="type" name="type" ng-model="Type" ng-disabled="1 == 0">
<option value=""></option>
<option value="1">A</option>
<option value="2">B</option>
</select>
<p ng-show="FormNameValidation.inctype.$error.required" class="help-block col-xs-12 col-sm-reset inline">Type is Required</p>
</div>
</div>
</form>
{{FormNameValidationStatus}} {{FormNameDirtyStatus}}
</form>
</div>





Output:


undefined undefined

Answer

A couple of issues ...

First, HTML5 does not support nested form elements but angular does with using the ng-form directive.

<form name="FormNameValidation" novalidate></form>

becomes

<ng-form name="FormNameValidation" novalidate></ng-form>

Second, you can simply name your form in your markup.

<form name="MainFormName" novalidate>

becomes

<form name="FormName" novalidate>

Which simplifies your controller function to:

$scope.showFormValidation = function(statusValid, statusDirty) {
   $scope.FormNameValidationStatus = statusValid;
   $scope.FormNameDirtyStatus = statusDirty;
};

You also had mismatched open/close tags in your HTML.

Here's a working plunk

Comments