Angular,在指令结束后调用一个函数

时间:2015-10-12 10:20:11

标签: javascript angularjs angularjs-directive

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

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

  

参考:http://doshprompt.github.io/angular-localization/

实施例

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

我需要知道sampleText注入p元素的时间,因为这会改变p的大小,我需要更新布局。

感谢。

2 个答案:

答案 0 :(得分:0)

您可以使用指令发布链接功能。这个函数将在元素处理结束时调用 - 因此文本应该已经被翻译过了。另请参阅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();
              });
          }    
        }
    };
});

答案 1 :(得分:0)

这不是解决问题的正确方法,但您可以通过编写指令来完成工作

<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
                }
            };
        });
相关问题