如何从指令刷新控制器?

时间:2013-11-14 11:20:13

标签: angularjs angularjs-directive angularjs-ng-repeat

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

在表格中,我显示了我的收藏品的每个值,一切都很好。但是当我删除列表中的一个元素时,控制器不会刷新。我选择一个指令,以便在每个元素后添加和删除一个编辑行。我需要jQuery,但也许有一种更优雅的方式来实现它。我认为缺少$watch$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();
          };
        }
    };
});

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

欢迎任何帮助。

1 个答案:

答案 0 :(得分: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