[英]Call Javascript After Directive Renders DOM for ShareThis
在Angular(1.3)應用程序中,我正在使用ng-repeat顯示記錄列表。 ng-repeat內部有一個帶有模板的指令。 在模板中,我使用的是ShareThis控件,該控件在加載DOM之后被激活。
首次加載應用程序時,ShareThis Javascript可以正常工作並激活按鈕。 在路線更改時,它不會激活。 我已經找到了通過stButtons.makeButtons()
或stButtons.locateElements();
手動激活控件的參考stButtons.locateElements();
,但是我不確定在指令或頁面周期中在何處調用此函數。 我已經嘗試過:
$timeout
或scope.$watch
<script>stButtons.locateElements();</script>
- 在模型綁定之前激活 我的理解是激活功能需要在綁定后和 DOM渲染后調用,但是Angular不知道DOM准備就緒的時間。 有一種方法可以僅使用Javascript動態呈現ShareThis控件,但是在這種情況下,我希望模板中定義的HTML不是Javascript。
我已經看到了幾個相關的問題,但是對於我的情況,似乎沒有一個答案能100%地起作用(並且從Angular 1.3開始,很多答案都已失效)。
item-list.html (查看)
<div ng-repeat="item in vm.itemList">
<item-directive item="item"></item-directive>
</div>
item-list.cs (控制器)
{ ... vm.itemList = getItems(...) ... }
item-directive.js (指令)
(function () {
angular.module('app');
function itemDirective() {
var directive = { templateUrl: 'item.html', link: linkFunc, controller: ItemDirective };
return directive;
function linkFunc(scope, element, attr, ctrl) { var item = scope.item }
}
ItemDirective.$inject = ['$scope'];
function ItemDirective($scope) { ... }
}
item.html (指令模板)
...
<div class="item-share-section">
<span class='st_sharethis_large' st_url="{{vm.item.url}}" st_title="{{vm.item.name}}"></span>
</div>
...
如果我很了解,您想在dom完全渲染后調用該函數,對嗎? 在您的指令的postLink中嘗試以下操作:
$scope.$watch('viewContentLoaded', stButtons.locateElements())
盡管我的解決方案有點破舊,但我仍然喜歡使用$ watch,因為這樣效率不高。 取而代之的是,我初始化了一個函數,該函數在呈現您要用來加載按鈕的特定視圖時加載按鈕。 該技術如下:
這是應該放在控制器中的函數:
$scope.loadShareThis = function() {
stButtons.makeButtons();
}
然后,您將像這樣添加到item-list.html中:
<div ng-repeat="item in vm.itemList" ng-init="loadShareThis()">
<item-directive item="item"></item-directive>
</div>
動態URL可能會給您帶來其他問題,但這又是另一個問題。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.