2013-05-03 40 views
7

我試圖從控制器的範圍獲取表單對象,當我得到一個名稱來形式。 它工作正常,但如果我用ng-switch創建表單,表單從不在範圍中顯示。與ng開關的角度形式

視圖

<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> 

控制器

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

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

如果刪除了NG-開關我可以看到從$範圍爲形式obj中的屬性 「theForm」。

任何想法如何做到這一點。我不想擁有不同名稱的兩種表格並使用ng-show。

這裏是例如「不工作」 http://plnkr.co/edit/CnfLb6?p=preview

+0

THX。花了一個小時。我得到的症狀是$ valid和$ dirty變得對我無效。 – ErichBSchulz 2014-12-20 12:01:30

回答

9

這是因爲ngSwitch創造了新的範圍。 (如果您查看console.log'd的範圍的$$childHead值,您可以在其中看到theForm,這是ngSwitch範圍)。

如果窗體將始終是相同的名稱,你可以簡單地把ngSwitch ES表單內:

<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> 
+0

謝謝,我的答案比我預想的要多得多。 – blackjid 2013-05-03 21:59:25

+1

除了使用'ng-switch on'作爲屬性外,我們可以將它用作單獨的標籤以提高可讀性。例如:' ...' – Abilash 2013-05-04 06:01:05

+1

@Abilash確實如此,但如果您關心IE 8及以下版本,請務必按照[Internet Explorer的[document.createElement]兼容性指南](http://docs.angularjs.org/guide/ie) – 2013-05-04 07:05:31