在Angular中,在指令end之后调用函数

Angular, call a function after directive end

本文关键字:之后 调用 函数 end 指令 Angular      更新时间:2023-09-26

我需要知道某个指令何时完成了它的工作。

指令它不是我的指令,它是我用来本地化一些文本的指令;它工作得很好。

裁判:http://doshprompt.github.io/angular-localization/

例子
<p i18n="locale.sampleText"></p>

我需要知道什么时候sampleText被注入到p元素,因为这改变了p的大小,我需要更新我的布局。

谢谢。

您可以使用指令发布链接函数。这个函数将在元素处理结束时被调用——所以文本应该已经翻译好了。参见http://www.undefinednull.com/2014/07/07/practical-guide-to-prelink-postlink-and-controller-methods-of-angular-directives/

<p i18n="locale.sampleText" post-process></p>
app.directive('postProcess', function () {
    return {
        restrict: 'A',
        link: {
          post: function(scope,elem,attr){
              $timeout(function() {
                  doPostProcess();
              });
          }    
        }
    };
});

这不是解决您的问题的正确方法但是您可以通过编写指令

来完成您的工作
<p i18n="locale.sampleText" check-content-loaded></p>

指令看起来像

myModule.directive('checkContentLoaded', function ($interval) {
            return {
                restrict: 'A',
                link: function (scope, element, attrs) {
                    var interval = $interval(function () {
                        console.log('still not found');
                        if (element.text()) {
                            $interval.cancel(interval);
                            console.log('found'); //here you can change your layout
                        };
                    }, 1000); //changing time interval you can improve performance
                }
            };
        });