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

4

1 回答 1

9

这是因为ngSwitch创建了新的范围。(如果您查看$$childHeadget console.log'd 的范围的值,您可以看到theForm它的内部。这就是ngSwitch范围)。

如果表单总是同名,您可以简单地将ngSwitches 放在表单中:

<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>
于 2013-05-03T21:34:15.210 回答