1

很长一段文章的道歉 - 我希望它不会让太多人离开。我拥有的是工作,但我不确定它是否是“正确”的做事方式,所以我只是寻求一些建议。AngularJS:DOM操作一旦查看完全加载

我有一个页面,我正在使用窗口大小来计算在哪里定位动态数量的元素。这些元素根据窗口的大小分开,然后使用Canvas元素绘制将每个元素连接到中心元素的线条。

我遇到的问题是知道什么时候所有元素都已经创建好了,现在可以调整大小和定位了。

我的HTML是这样的:

<div class="panel"> 
     <div class="panel_content"> 
      <div class="input_mapping" ng-repeat="input in inputs" mapping-resize> 
       {{input.name}} 
      </div> 
     </div> 
    </div> 
    <div class="panel"> 
     <div class="panel_content"> 
      <div class="central_mapping"> 
       {{mapping.name}} 
      </div> 
     </div> 
    </div> 
    <div class="panel"> 
     <div class="panel_content"> 
      <div class="output_mapping" ng-repeat="output in outputs" mapping-resize> 
       {{output.name}} 
      </div> 
     </div> 
    </div> 

我使用的指令,映射调整大小,但运行在每个NG-重复来调整一切。真的,我只想运行一次,一旦创建了所有的子元素,但是如果我将指令放在父div(panel_content)上,它并不知道指令运行时的子元素,重新定位它们。目前

我的指示是:

app.directive('mappingResize', ['$timeout', function($timeout) { 
    return function(scope, elem, attrs) { 

     if(scope.$last) { 
      $timeout(function() { 
       positionElements(); 
      }); 
     } 
    } 
}]); 

positionElements()是,因为它表明,那里有我所有的代码是用于定位的元素一旦被创建。它工作得很好,尽管它可能以更“角度的方式”来完成(这只是一个标准的JS函数,它依赖于全面的jQuery)。

在指令中,我使用$ last属性,所以如果它是ng-repeat中的最后一个元素,我只需调用positionElements(),因为我需要知道它们的全部以正确定位它们。我也使用$ timeout,所以代码在页面呈现后排队运行。

我的问题是,这是我能做的最好的吗?

此刻,我调用了两次positionElements() - 一次用于输入映射ng-repeat,一次用于输出映射。真的,我只需要在创建所有映射元素时调用一次(并且只需调用一次)。 使用$ timeout和$ last也不是很好 - 感觉就像有些事件会告诉我视图已经创建,但是我发现的一切都是死路一条。

无论如何,对上述建议或建议将不胜感激。

回答

0

使用$超时,并在您的网页端移动的指令:

var app = angular.module('plunker', []); 

app.controller('MainCtrl', function($scope) { 
    $scope.model = { items: [1,2,3,4,5] }; 
}); 

app.directive('directive', function() { 
    return { 
    link : function (scope, elem, attrs) { 
     console.log(attrs.index); 
    } 
    } 
}); 

app.directive('lastDirective', function ($timeout) { 
    return { 
    link : function (scope, elem, attrs) { 
     $timeout(function() { 
     // position elements here 
     console.log(attrs.index); 
     }); 
    } 
    } 
}); 

HTML:

<body ng-controller="MainCtrl"> 
    <div ng-repeat="item in model.items" directive index="1"></div> 
    <div ng-repeat="item in model.items" directive index="2"></div> 
    <div last-directive index="3"></div> 
    </body> 

打开控制台查看指令执行顺序

http://plnkr.co/edit/Y1KIGAa7hDjY9STlmPm2?p=preview