gpt4 book ai didi

javascript - AngularJS: View 完全加载后的 DOM 操作

转载 作者:行者123 更新时间:2023-11-28 07:57:18 25 4
gpt4 key购买 nike

对这么长的帖子表示歉意 - 我希望它不会让太多人失望。我所拥有的正在工作,但我只是不确定这是否是“正确”的做事方式,所以我只是在寻找一些建议。

我有一个页面,我使用窗口大小来计算动态数量的元素的位置。这些元素根据窗口的大小进行间隔,然后我使用 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>

我使用指令mapping-resize来调整所有内容的大小,但这在每个ng-repeat上运行。实际上,我只想运行一次,一旦创建了所有子元素,但如果我将指令放在父 div (panel_content) 上,它在指令运行时不知道子元素,所以也不会不要重新定位它们。

我的指令目前是这样的:

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

if(scope.$last) {
$timeout(function() {
positionElements();
});
}
}
}]);
正如它所暗示的,positionElements() 是我所有代码用于在创建元素后定位元素的位置。它工作得很好,尽管它可能可以用更“Angular 方式”来完成(它只是一个依赖于成熟的 jQuery 的标准 JS 函数)。

在指令中,我使用 $last 属性,因此仅当它是 ng-repeat 中的最后一个元素时才调用positionElements(),因为我需要了解所有这些元素才能正确定位它们。我还使用 $timeout,以便代码在页面渲染后排队运行。

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

目前,我调用positionElements()两次——一次用于输入映射ng-repeat,一次用于输出映射。实际上,当所有映射元素都已创建时,我只需要调用它一次(并且仅一次)。使用 $timeout 和 $last 感觉也不太好 - 感觉好像会有一些事件告诉我 View 已经创建,但我发现的一切都是死胡同。

无论如何,我们将不胜感激对上述内容的建议或意见。

最佳答案

使用 $timeout 并将指令移至页面末尾:

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

关于javascript - AngularJS: View 完全加载后的 DOM 操作,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25931677/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com