0

这是演示:http ://plnkr.co/edit/atZZXM6YVYQL0SilpWxq?p=preview

在一个表格中,我显示了我收藏的每个值,一切都很好。但是当我删除列表中的一个元素时,控制器不会刷新。我选择了一个指令,以便在每个元素之后添加和删除编辑行。我需要这样做jQuery,但也许有一种更优雅的方式来实现它。我想一个$watchor$broadcast丢失了。

HTML

<table>
    <tr ng-repeat="item in items" item-directive="item"></tr>
    <tr>
      <td>Total</td>
      <td>{{getTotal()}}</td>
    </tr>
</table>

AngularJS

app.directive("itemDirective", function($compile){
  var trLine = '<tr><td>{{itemDirective.name}}</td><td>{{itemDirective.value}}</td>'
          +'<td><button ng-click="edit()">Edit</button></td>'
          +'<td><button ng-click="remove()">Remove</button></td>'
          +'<td><button ng-click="removeFromController()">Remove from controller</button></td>'
          +'</tr>';
  var trEditLine = '<tr class="editLine"><td style="background: #E6E6E6"><div>'
          +'<button ng-click="done();">Done</button>'
          +'<button  ng-click="cancel();">Cancel</button></div></td>'
        +'</tr>';
    return {
        template: trLine,
        replace: false,
        scope: {
          itemDirective: '='
        },
        link: function(scope, element, attrs) {
          scope.edit = function() {
            if(!element.edited) {
              element.edited = true;
              element.after($compile(trEditLine)(scope));
            }
          };
          scope.cancel = function() {
            element.edited = false;
            $(".editLine").remove();
          };
          scope.done = function() {
            element.edited = false;
            $(".editLine").remove();
          };
          scope.remove = function() {
            element.remove();
          };
        }
    };
});

这将按预期删除该行,但总数不会改变。

欢迎任何帮助。

4

1 回答 1

1

我会提供removeFromController()指令方法(因为您使用隔离范围)并编写ng-repeat如下:

 <tr ng-repeat="item in items" item-directive="item" invoke="removeFromController()">

现在指令:

scope: {
      itemDirective: '=',
      invoke: '&'
    },

trLine

var trLine = '<tr><td>{{itemDirective.name}}</td><td>{{itemDirective.value}}</td>'
          +'<td><button ng-click="edit()">Edit</button></td>'
          +'<td><button ng-click="remove()">Remove</button></td>'
          +'<td><button ng-click="invoke()">Remove from controller</button></td>'
          +'</tr>';

见已编辑Plunker

于 2013-11-14T12:08:20.577 回答