1

我有一个元素,我使用$swipe .bind (来自ngTouch)来连接控制器构造函数中的一些事件处理程序:

$swipe.bind($(element_selector), {'move': dragMoveHandler});

我将该元素移动到 ngInclude 中,但现在控制器构造函数在 Angular 处理 ngInclude 之前运行,因此$swipe.bind调用在执行$(element_selector)undefined会失败。

我研究了使用$includeContentLoaded来检测 ngInclude 何时被处理,但不清楚每次触发时加载了哪个 ngInclude,因此我的代码需要计算已加载的包含数,然后才能知道它是安全的使用$swipe.bind,这似乎不是一个强大的解决方案。

我怎样才能做到这一点?

4

1 回答 1

4

为什么不简单地在 $includeContentLoaded 被触发时检查元素是否存在

$rootScope.$on('$includeContentLoaded', function(event) {
   if($(element_selector).length){
       $swipe.bind($(element_selector), {'move': dragMoveHandler});
   }
});

或者如果您想避免注入 $rootScope 并使用角度事件,为什么不简单地以简单的原生 JavaScript 方式执行此操作

setTimeout(function check_if_element_exist(){
   if($(element_selector).length){
       $swipe.bind($(element_selector), {'move': dragMoveHandler});
   }
   else {
       setTimeout(check_if_element_exist, 0);
   }
}, 0);

您甚至可以将此逻辑移至装饰性指令,以免违反 SoC 原则。

于 2014-12-11T17:29:15.143 回答