【问题标题】:Add "A"-directive to parent node and execute将“A”指令添加到父节点并执行
【发布时间】:2016-07-02 21:26:10
【问题描述】:

我是 Angular.js 的新手,但遇到了一个问题。

我想集成这个插件 (https://github.com/pratyushmittal/angular-dragtable) 以便能够在我的表格中拖动列。
整个表是一个指令。每个<th> 也通过指令呈现。

   <table>
     <thead>
       <tr>
         <th ng-repeat="col in table.columns" my-column></th>
       </tr>
     </thead>
   </table>

根据插件文档,我需要将 draggable 指令设置为 table。如果我手动设置它,它不会正确抓取我的列,因为此时没有呈现这些列,这不起作用。在 my-column 指令中,我正在等待最后一个

.directive('myColumn', ['$timeout', function($timeout) {
  return {
    restrict: 'A',
    templateUrl: 'templates/column.html',
    link: function(scope, element, attrs) {
      if (scope.$last)
        $timeout(function() {
            //scope.$emit('lgColumnsRendered');
            angular.element(element).closest('table').attr('draggable', 'draggable');
        });
    }
  }
}])

当最后一次渲染时,我走到我的桌子前并设置了这个指令。可以肯定的是,它很愚蠢并且不起作用。我还阅读了有关 $compile 的信息,但我需要将属性指令添加到我的 DOM 中已经存在的表中。

也许我走错了路,不明白这样做的概念,但你明白了吗?我怎样才能做到这一点?

【问题讨论】:

  • 我的回答对解决问题有帮助吗?如果没有 - 请对其发表评论,以便我们找到解决方案。如果它对您有用 - 请考虑将答案标记为已接受,以便其他人现在问题已解决。

标签: javascript angularjs html-table draggable angular-directive


【解决方案1】:

问题是 angular-dragtable 不希望表列是动态的。 而且我认为这是合乎逻辑的假设 - 在大多数情况下,表 rows 将是动态的(这对于拖动表来说是可以的),但列通常是静态的。

解决方案是在创建列时向 dragtable 添加一个特殊事件,要求它重新初始化,这是我对 dragtable 所做的修改(请参阅下面的完整源链接):

project.directive('draggable', function($window, $document) {
    function make_draggable(scope, elem) {
        scope.table = elem[0];
        scope.order = [];
        scope.dragRadius2 = 100;

        var headers = [];
        init();

        // this is the event we can use to re-initialize dragtable 
        scope.$on('dragtable.reinit', function() {
            init();
        });

        function init() {
            headers = scope.table.tHead.rows[0].cells;
            for (var i = 0; i < headers.length; i++) {
                scope.order.push(i);
                headers[i].onmousedown = dragStart;
            }
        }

        function dragStart($event) {

现在您可以在您的代码中执行此操作:

    .directive('myColumn', ['$timeout', '$rootScope', function($timeout, $rootScope) {
      return {
        restrict: 'A',
        templateUrl: 'templates/column.html',
        link: function(scope, element, attrs) {
          if (scope.$last)
            $rootScope.$broadcast('dragtable.reinit');
        }
      }

这是我测试问题的示例的full code

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2018-01-05
    • 2017-12-29
    • 1970-01-01
    • 2021-11-23
    • 2020-08-25
    • 2015-03-20
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多