2

I am trying to access a html defined form in the $scope in the controller. The thing is that the form is under ng-switch directive so I was suspecting this is the issue. Still, I couldn't find any solution to this.

My code is :

<div ng-switch="bla">
   <div ng-switch-when="blabla">
       <form name="myForm">
       </form>
    </div> 
</div>

And the js : $scope.myForm is returning undefined.

Can you please help me with this?

Thanks in advance.

4
  • it should be {{myForm}} when writing the scope variable on html page Commented Jan 12, 2018 at 8:57
  • @RakeshBurbure , I want to use it in a javascript file, not in the page. Commented Jan 12, 2018 at 8:59
  • js code please? Commented Jan 12, 2018 at 9:02
  • Here is an example : jsfiddle.net/PW2rQ/17 Commented Jan 12, 2018 at 9:08

2 Answers 2

1

Yes, you are right: This directive creates new scope. Like ng-if. See: https://docs.angularjs.org/api/ng/directive/ngSwitch

Here could be an answer: https://github.com/angular/angular.js/issues/10944 https://github.com/angular/angular.js/wiki/Understanding-Scopes#ng-include

If you need the form in a method in the controller, that you call from the html code, you can use the form as a parameter.

For instance:

<form name="dataForm" ng-submit="$parent.processForm(dataForm)">

processForm is a method in the controller. You need $parent here because of the child scope under ng-switch.

Sign up to request clarification or add additional context in comments.

1 Comment

Thanks for the answer. I tried that, but it still doesn't work, I can't figure out why...
0
  1. check that condition for div "ng-switch-when " is true i.e "blabla" is true or not . because form will be there only if the condition is true

  2. If it is not working then try to declare form object in your controller (at the time when controller loads ). like this

$scope.myForm ={};

Hope it will work ........

1 Comment

Thank you for your answer. Sadly, I still need the form object to apply some functions on it. If I define it like that, it will be a simple js object, and I cannot call setValidity for example.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.