JQuery不检测角指令中的DOM元素。

时间:2022-12-02 15:59:11

I have an angular directive with a linked template which has a simple code block

我有一个带链接模板的角指令,它有一个简单的代码块

<div>
  <h1 class="dfaded">Hello World</h1>
</div>

Now at the end of my index.html file I am putting a Javascript Function

在指数的最后。我正在放一个Javascript函数。

<script>
$(document).ready(function () {
    $('.dfaded').addClass("ahidden").viewportChecker({
        classToAdd: 'avisible animated fadeIn',
        offset: 100
    });
});
</script>

But this function doesn't work. On further debugging , even if I put a simple function like

但是这个函数不行。进一步调试,即使我放一个简单的函数,比如

$('.dfaded').hide();

It is still not working. Now if I put this HTML block OUTSIDE the directive - everything works fine. So most probably JQuery is not recognizing the DOM elements which I put inside the Angular Directive.

它仍然不起作用。现在,如果我把这个HTML块放到指令外面——一切都很好。所以很可能JQuery没有识别我放在角指令中的DOM元素。

I have added the jquery files after all the directive files have been loaded in the HTML page. Any help would be really appreciated.

在HTML页面中加载了所有指令文件之后,我添加了jquery文件。如有任何帮助,我们将不胜感激。

1 个解决方案

#1


3  

Your jQuery script runs before Angular processes and renders template file. This is one of the reasons why you should not work with jQuery in Angular project the way you are used to.

jQuery脚本在角化进程和呈现模板文件之前运行。这就是为什么不应该像以前那样在角度项目中使用jQuery的原因之一。

In order to make it work properly wrap the viewportChecker plugin initialization into custom directive. It can look for example like this:

为了使其正常工作,将viewportChecker插件初始化封装到自定义指令中。例如:

app.directive('viewportChecker', function() {
    return {
        link: function(scope, element) {
            element.addClass("ahidden").viewportChecker({
                classToAdd: 'avisible animated fadeIn',
                offset: 100
            });
        }
    };
});

Then you would attach this directive to necessary tag:

然后你将把这个指令附加到必要的标签上:

<div>
    <h1 class="dfaded" viewport-checker>Hello World</h1>
</div>

#1


3  

Your jQuery script runs before Angular processes and renders template file. This is one of the reasons why you should not work with jQuery in Angular project the way you are used to.

jQuery脚本在角化进程和呈现模板文件之前运行。这就是为什么不应该像以前那样在角度项目中使用jQuery的原因之一。

In order to make it work properly wrap the viewportChecker plugin initialization into custom directive. It can look for example like this:

为了使其正常工作,将viewportChecker插件初始化封装到自定义指令中。例如:

app.directive('viewportChecker', function() {
    return {
        link: function(scope, element) {
            element.addClass("ahidden").viewportChecker({
                classToAdd: 'avisible animated fadeIn',
                offset: 100
            });
        }
    };
});

Then you would attach this directive to necessary tag:

然后你将把这个指令附加到必要的标签上:

<div>
    <h1 class="dfaded" viewport-checker>Hello World</h1>
</div>