2015-11-04 68 views
1

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

但是,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 
    } 
    } 
}) 

这种方法是否正确?或者我应该如何定期写作?

谢谢!

回答

1

你在找什么是$timeout(fn)
fn将在控制器呈现后调用。

+0

Yeap,直接使用'$ timeout(fn)'。有用!所以'$ timeout'的函数只会在模板编译和加载后运行,对吧? – KobeLuo

+0

是的,当我需要jquery的效果时,我多次在angularJs中使用'$ timeout'。 – user5488195