如何绑定一个jQuery事件与AngularJS动态内容 [英] How to bind a jQuery event to dynamic content with AngularJS

查看:131
本文介绍了如何绑定一个jQuery事件与AngularJS动态内容的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

基本上在我的控制器,我在做一个 $ http.get()加载一些HTML设置当前视图。我的问题是,我无法弄清楚如何使用这个新的动态内容重新绑定jQuery的事件。

Basically in my controller, I'm doing an $http.get() to load some html to set a "current view". My issue is that I can't figure out how to rebind the the jQuery event with this new dynamic content.

现在,我已经使出somethign这样的:

Right now, I've resorted to somethign like this:

$http.get('/someurl', {}).success(function(data){
  $scope.detailedView = data;
  // Now here comes the rebinding
  setTimeout(function(){
    // Use jquery to bind the new content
  }, 1500);
});

我一直在寻找一个解决方案,以及任何有关我找到点用一个指令。我已经研究过这一点,但我不知道怎么指令将被用于这样的事情。

I've been looking for a solution, and anything related that I've found points to using a directive. I've looked into this, but I do not know how a directive would be used for something like this.

注意无超时,之前运行动态内容实际上是在DOM绑定。我也试着找到的东西,这将是类似于挂钩到东西后$应用将运行,但没有发现类似的事情。

Note without the timeout, the bindings run before the dynamic content is actually in the DOM. I've also tried finding something that would be similar to hooking into something after the $apply would run but have not found anything similar.

推荐答案

首先应该看到,如果你正在使用jQuery做什么,不能用角来完成。

First should see if what you are doing with jQuery can't be done using angular.

下面是一个可以使用的指令的​​最简单的版本:

Here's the most simplistic version of a directive that can be used:

<div ng-repeat="item in items" my-directive>Item {{$index+1}}</div>

app.directive('myDirective', function ($timeout) {
    return function (scope, element, attrs) {
        $timeout(function () {
            /* element is a jQuery object when jQuery loaded in page before angular,*/
            /* otherwise is a jQlite object that has many of same methods as jQuery*/
            element.css({ 'border': '1px solid green', 'margin': '10px 30px','padding':'5px'});
        }, 0);
    }
 });

下面是一个使用长超时生成使用该指令重复项目的数据演示:

Here's a demo that uses a long timeout to generate data for repeated items that use the directive:

http://jsfiddle.net/AXYGL/

这篇关于如何绑定一个jQuery事件与AngularJS动态内容的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆