【问题标题】:How can I use $swipe.bind (ngTouch) on an element inside an ngInclude?如何在 ngInclude 内的元素上使用 $swipe.bind (ngTouch)?
【发布时间】:2014-12-01 06:25:29
【问题描述】:

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

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

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

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

我该怎么做?

【问题讨论】:

  • 请创建一个可播放的 sn-p 演示您的问题。
  • 在 fiddle 或 plunkr 中显示基础
  • 您最好使用某种“可滑动”指令来处理每个元素的事件绑定。

标签: javascript angularjs angularjs-ng-include angularjs-ng-touch


【解决方案1】:

当 $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 原则。

【讨论】:

    猜你喜欢
    • 2013-12-10
    • 1970-01-01
    • 2012-07-03
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-09-05
    相关资源
    最近更新 更多