Ng form nested in ng switch

I am having a problem with an ng form that does not create a form in an area when it is nested in an ng area.

for instance

<div ng-controller='TestCtrl'> <ng-switch on="switchMe"> <div ng-switch-default>Loading...</div> <div ng-switch-when="true"> <form name="nixTest"> <input placeholder='In switch' ng-model='dummy'></input> <button ng-click="test()">Submit</button> </form> </div> </ng-switch> </div> 

Controller:

 controllers.TestCtrl = function ($scope) { $scope.switchMe = true; $scope.test = function () { if ($scope.nixTest) { alert('nixTest exists') } else { alert('nixTest DNE') } } } 

Are there any problems? Test script can be found here.

+4
source share
2 answers

ng-switch creates a child region, and a form is created in this region. Therefore, the form of the child is not available in the parent area.

To access it, you can pass it to the test() method as ng-click=test(nixTest) . Thus, the signature of the scope method must also be updated to support the input parameter.

+3
source

I ran into the same problem. Unfortunately, I couldn’t easily apply the Chandermani solution, because I need to access the form name from a call to $on within the parent area of ng-switch . Thus, I resorted to creating a directive that sends the form name to $rootScope :

 .directive("globalName", ["$rootScope", function($rootScope) { return function(scope, element) { $rootScope["get_" + element.attr('name')] = function() { return scope[element.attr('name')]; }; } }]); 

Usage looks like this:

 <form name="whatever" novalidate global-name>...</form> 

and then you get access to the form in controllers, for example. eg:

 $scope.get_whatever().$setPristine(); $scope.get_whatever().$setUntouched(); 

Being a name in $rootScope , it no longer depends on your DOM structure.

I understand that this is not an optimal solution because it pollutes the global namespace, but I feel uncomfortable with the visibility of the form name depending on the structure of the DOM in several unexpected ways.

0
source

Source: https://habr.com/ru/post/1498987/


All Articles