Angular forms with ng-switch
Asked Answered
C

1

7

I'm trying to get a form object from the scope of a controller when I get a name to de form. It work fine, but if I create the form with a ng-switch, the form never shows in the scope.

the view

<body ng-controller="MainCtrl">

    <div ng-switch on="type">
      <form name="theForm" ng-switch-when="1">
        <label>Form 1</label>
        <input type="text"/>
      </form>
      <form name="theForm" ng-switch-when="2">
        <label>Form 2</label>
        <input type="text"/>
        <input type="text"/>
      </form>

    </div>

    <button ng-click="showScope()">Show scope</button>
</body>

the controller

app.controller('MainCtrl', function($scope) {
  $scope.type = 1;

  $scope.showScope = function(){
    console.log($scope);
  };
});

If I remove the ng-switch I can see the property "theForm" from the $scope as the form obj.

Any idea how to do it. I don't want to have the two forms with different names and use ng-show.

Here is the example "not-working" http://plnkr.co/edit/CnfLb6?p=preview

Cammiecammy answered 3/5, 2013 at 21:25 Comment(1)
thx. spent an hour on this. the symptom I got was that $valid and $dirty became unavailable to me.Siusan
H
9

This is because ngSwitch creates new scope. (If you look at the $$childHead value of the scope that get's console.log'd, you can see theForm inside it. This is the ngSwitch scope).

If the form will always be the same name, you can simply put the ngSwitches inside the form:

<form name="theForm">
  <div ng-switch on="type">
    <div ng-switch-when="1">
      <label>Form 1</label>
      <input type="text"/>
    </div>
    <div ng-switch-when="2">
      <label>Form 2</label>
      <input type="text"/>
    </div>
  </div>
</form>
Howsoever answered 3/5, 2013 at 21:34 Comment(4)
Thanks, I learned a lot more than I expected with your answer.Cammiecammy
Instead of using ng-switch on as a attribute, we can use it as a separate tag to make more readable. Ex: <ng-switch on="ur swich condition">...</ng-switch>Workday
@Workday True, but if you care about IE 8 and below, be sure to use document.createElement as per the Internet Explorer Compatability guideHowsoever
@Brandon I think this works fine on IE8 as well. I've used it in my application and fortunately there were no problems until today.Workday

© 2022 - 2024 — McMap. All rights reserved.