2016-03-26 1 views
2

私はAngularJSを使い慣れていませんし、ng-repeatでネストされたカスタムディレクティブの特定の要素を削除することに問題があります。 Here is my plunker角。 ng-repeatでネストされたディレクティブで削除する

私は、ネストされたディレクティブのような構造を持っている:私は必要と親モデルのアップデートとして

<button ng-click="mc.addCat()">Add Category</button> 

    <category ng-repeat="cat in mc.main.categories"> 
     <ul class="first-level"> 
      {{ $index +1 }}. Category 
      <br> 
      <input type="text" ng-model="mc.main.categories[$index].name"> 
      <button ng-click="cc.removeCat($index)">Del Category</button> 
      <button ng-click="cc.addItem()">Add Item</button> 

      <item ng-repeat="item in cc.cat.items track by item.id"> 
       <li class="second-level"> 
       {{ $parent.$index +1 }}.{{ $index +1 }} 
       <input type="text" ng-model="mc.main.categories[$parent.$index].items[item.id].name"> 
       <button ng-click="ic.removeItem(item)">del</button> 
       </li> 
      </item> 
     </ul> 
    </category> 

カテゴリの追加と削除が動作します。 しかし、アイテムフィールドに何かを入力してから削除すると、このアイテムは親モデルに残ります。

ネストされたスコープの問題を考えると、何が間違っているのか教えていただけますか?

ありがとうございます!

答えて

1

削除機能は、メインモデルを更新するメソッドを呼び出す必要があります....私はplunkerを編集しましたおよび編集をフォーク....

`

$scope.$on('updateItems',function(event,index,pindex){ 
     console.log(index); 
     console.log(pindex); 
     var sti = ""+index+""; 
     delete vm.main.categories[pindex].items[sti]; 
}); 

`
はここにあります。plunker

+0

あなたの懸念をお寄せいただきありがとうございます!しかし、私はアイテムを追加し、任意の削除し、新しい1つ以上を追加し、削除しようとすると、親モデルから特定の項目を削除します。それはすべて1つの最初のカテゴリにあり、それ以上のカテゴリは追加されません。 – polisvit

+0

あなたに多くの感謝!今はそれが必要なように働いています! – polisvit

+0

私の答えを受け入れてください... –

0

私はあなたのコードから理解するものから、あなたの新しいitemが追加されていると、あなたの親モデルを更新しているいくつかのinformationを入力している....

<input type="text" ng-model="mc.main.categories[$parent.$index].items[item.id].name"> 

の項目を削除しながら、あなたが削除されていますコピーと元のオブジェクト。カテゴリ内

$scope.$on('delItem', function(event, data){ 
    var items = vm.cat.items; 
    items.splice(items.indexOf(data), 1); 
}); 

すべて以下の機能が動作していないことのようです。..ディレクティブで

vm.cat = { 
    items: [{ 
     id: 0, 
     name: '' 
    }] 
}; 
vm.itemId = 0; 
vm.addItem = function() { 
    vm.itemId = vm.itemId + 1; 
    var item = { 
     id: vm.itemId, 
     name: '' 
    }; 
    vm.cat.items.push(item); 
}; 
$scope.$on('delItem', function(event, data) { 
    var items = vm.cat.items; 
    items.splice(items.indexOf(data), 1); 
}); 
+0

はい、アイテムをカテゴリに追加し、親モデルを変更する必要があります。アイテムの入力に何か入力すると更新されますが、スプライスメソッドでアイテムを削除すると親モデルに変更はありません – polisvit

関連する問題