【问题标题】:Angular directives do not emit 'viewContentLoaded' eventAngular 指令不会发出“viewContentLoaded”事件
【发布时间】:2015-11-04 03:34:53
【问题描述】:

我写了一个'light-gallery'指令。它需要jquery.lightgallery.js插件来初始化$.fn.lightGallery()函数,这些函数必须在指令模板编译和加载后执行。

但是,Angular 指令不会在 link 函数中发出“viewContentLoaded”事件。所以我想问一下如何知道指令模板何时编译和加载?

现在我使用$timeout 来侦听已编译的范围值。编译范围值后,可以运行oncompiled 函数。看:

myApp.directive("light-gallery", function(){
  return {
    restrict: "E",
    scope: {},
    replace: true,
    template: '<div compiled="{{compiled}}"></div>',
    link: function(scope, elem, attrs){
      var onCompiled = function(){
        $("#lightgallery").lightGallery();
      };

      var recur = function(){ 
        // when the attr `compiled` values `true`
        // it means template compiled and loaded
        if("true" === elem.attr("compiled")){
          onCompiled();
        }else{
          setTimeout(recur, 100);
        }
      };
      recur();

      // to tell template compiled
      scope.compiled = true
    }
  }
})

这种方法正确且规律吗?或者我应该如何定期写作?

谢谢!

【问题讨论】:

    标签: javascript jquery angularjs


    【解决方案1】:

    你要找的是$timeout(fn)
    fn 将在你的控制器渲染后被调用。

    【讨论】:

    • 是的,直接使用$timeout(fn)。有用!所以$timeout的函数只有在模板编译加载后才会运行,对吧?
    • 是的,当我需要Jquery的效果时,我在angularJs中多次使用$timeout
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-09-28
    • 2014-01-04
    • 1970-01-01
    • 2016-04-29
    • 2017-04-01
    • 1970-01-01
    相关资源
    最近更新 更多