2013-04-01 21 views
0

我有一個對象,表示有兩個孩子的「討論」或「辯論」 - 每個孩子是辯論中表示「爭論」的孩子對象的集合。一個孩子是一個「肯定」的爭論集合,另一個是「負面」的爭論。

我使用的是這樣的:

<div ng-controller="contentionGroupCtrl" ng-repeat="(contentionType, contentionGroup) in debate.contentions_sorted" class="contention {[{contentionType}]}-section"> 
    <a class="button contention-new" ng-click="toggleEditForm()">+ Add New Contention</a> 
    <div class="contention-new" ng-show="editing"> 
    <form ng-submit="formContentionSubmit()" class="ng-scope ng-pristine ng-invalid ng-invalid-required"> 
     <input type="text" id="contention_name" name="contention[name]" required="required" ng-model="edit.name" placeholder="New Contention" class="ng-pristine ng-invalid ng-invalid-required"> 
     <div> 
     <input type="radio" id="contention_aff_0" name="contention[aff]" required="required" ng-model="edit.aff" value="1"> 
     <label for="contention_aff_0" class="required">Affirmative</label> 
     <input type="radio" id="contention_aff_1" name="contention[aff]" required="required" ng-model="edit.aff" value="0"> 
     <label for="contention_aff_1" class="required">Negative</label> 
     </div> 
     <input type="button" ng-click="toggleEditForm()" value="Cancel"> 
     <input type="submit" value="Save"> 
    </form> 
    </div> 
    <div ng-controller="contentionCtrl" ng-repeat="contention in contentionGroup" class="contention" id="contention-{[{ contention.id }]}"> 
    EACH CONTENTION CONTENT STUFF HERE 
    </div> 
</div> 

這顯示兩組的爭奪,並且每個人都有一個「添加新爭」的形式在頂部。基於toggleEditForm()方法切換表單。我爲「新爭用」和「編輯爭用」使用了相同的表單模板,因此該表單有一個模型(單選按鈕),用於爭用是否爲「肯定」或「否定」爭用。

控制器「contentionGroupCtrl」是集團的爭論,它的toggleEditForm方法是這樣的:

// Toggle New Contention Form 
    $scope.toggleEditForm = function() { 
    var ct; 
    $scope.editing = !$scope.editing; // First display or hide the form 
    if ($scope.editing == true) { // If displaying the form, initialize 
     if ($scope.contentionType == 'aff') { 
     ct = 1; // 'aff' equates to 1 in the model 
     } 
     else { 
     ct = 0; 
     } 
     $scope.edit.aff = ct; // Sets the radio button appropriately 

     // We are now editing 
     $scope.edit.name = ''; // Blanks out the contention "Name" field for creating a new contention 
    } 
    }; 

一切都很正常,除了:比方說,你在打開的「肯定」 - 側「添加新爭用「形式。它會顯示一個空白的名稱,並選擇單選按鈕「肯定」。如果您再點擊「否定」旁邊的「添加新爭用」按鈕,將出現相應的表格,但兩個「名稱」字段將被刪除,並且單選按鈕將被選爲「否定」。

$範圍應該在每邊不同,不是嗎?每個表單使用它自己的$ scope.edit模型;爲什麼要修改負面爭用方的「edit.name」和「edit.aff」模型會影響肯定方?

+5

jsfiddle或plunker中的簡單演示覆制問題,並讓人們更好地看到cotrollers範圍層次結構會有所幫助 – charlietfl

+0

好的!我會稍後再嘗試。我剛剛嘗試過,但時間太長了!謝謝你的好建議。 – Offlein

+1

定義'$ scope.edit'在哪裏?如果它是在'contentionGroupCtrl'上方的控制器中定義的(即,在'ng-repeat'之上),則由於JavaScript原型繼承的作用方式,所有子控制器將共享相同的單個'$ scope.edit'對象。 –

回答

1

基於我從問這個問題以及從Mark Rajcok的建議中學到的知識,這個問題的主要焦點是我嵌套了Scopes,這不是最佳實踐。

在我的情況下,我依賴的其他$ scope變量需要在子範圍內初始化,否則它們從父範圍繼承。這完全是我爲拍攝的,但它最終只是讓我的實現感到困惑,而我錯過了修復它。

但是比任何事情都更重要:儘量不要嵌套示波器!相反,使用自定義服務處理控制器之間的數據接口。

相關問題