2016-05-29 2 views
0

ユーザーがセクションを追加できるサンプルコードがあり、セクションの下にサブセクションを追加できます。セクションとサブセクションはsortableですui-sortableを使用していますが、アイテムをソートするとセクション1をセクション2にスワップしてからセクション2に新しいサブセクションを追加しようとすると問題が発生し、セクション1に新しい要素が追加され、項目は、ここで第2ソート後に親セクションを修正するサブセクションを追加する - 角型JS

の下に追加されなければならない私のデモですが、正常に動作しません:Complete Code

私の質問は、私はセクションを並べ替えた後、正しい親セクションに新しいサブセクションを追加する方法です。セクションをソートした後、サブセクションを追加しても正しく動作しないためです。サブセクションが間違った親セクションに移動します。

マイHTML

<ul ui-sortable="sortableOptions" ng-model="section" class="list"> 
    <li ng-repeat="parent in section"> 
     <span>Section {{parent.id}}</span> 
     <ul ui-sortable="sortableOptions" ng-model="subSection" class="list"> 
      <ol ng-repeat="child in subSection" ng-if="child.parentId == parent.id"> 
       <span>SubSection {{child.id}}</span> 
      </ol> 
      <button ng-click="addSubSection($index + 1)">Add SubSection</button> 
     </ul> 
    </li> 
</ul> 

<button ng-click="addSection()">Add Section</button> 

私のJS

var myApp = angular.module('myApp',['ui.sortable']) 

.controller('MyCtrl', ['$scope', function($scope) { 
    $scope.section = [{id: 1}, {id:2}]; 
    $scope.subSection = [{id:1, parentId: 1}, {id:2, parentId: 1}, {id:3, parentId: 2}]; 

    $scope.addSection =function(){ 
     var newId = $scope.section.length +1; 

     $scope.section.push({id: newId}); 
    }; 

    $scope.addSubSection = function(parentIndex) { 
     var newSubId = $scope.subSection.length + 1; 
     $scope.subSection.push({id:newSubId, parentId:parentIndex}); 
    }; 
}]); 

私ははっきりとそれを説明希望。ありがとうございました

+0

質問を削除して再投稿しているようです。これは質問禁止につながる可能性が高い。注意が必要な場合、私はそれに恩恵を与えることをお勧めします。 –

答えて

2

$indexは信頼できないようですが、理由はよく分かりませんが(下記参照)この問題の作業溶液:

  1. 変更addSubSection()代わりに、インデックスの親対象取る:

    $scope.addSubSection = function(parent) { 
        var newSubId = $scope.subSection.length + 1; 
        $scope.subSection.push({id:newSubId, parentId:parent.id}); 
    }; 
    
  2. は、テンプレートから親を渡します

    <button ng-click="addSubSection(parent)">Add SubSection</button> 
    

枝打ちされた大柄:https://plnkr.co/edit/BFR6JLngJiFztR5P6dWa?p=preview


サブセクションを並べ替えるとき、内側の並べ替えが機能しません。モデルがどのように表現されているか、すなわちすべてのサブセクションがフラットな配列にあり、ビュー内の親に配置されている(つまり、ng-if)、バグが発生していると思います。サブセクションをセクションごとに別々の配列に分割するほうがよいでしょう。 ng-repeatの範囲を使用するか、セクションのサブセクションをそのモデルに配置します(例: $scope.section = [{id: 1, subSections: [...]}, {id:2, subSections: [...]}];

+0

これは私が探しているものです。ご協力いただきありがとうございます :) – jamcoder

関連する問題