在angularJS应用文档就绪事件中运行jquery代码



我正在尝试在 angular 应用程序中运行一些 jquery 代码,我尝试运行的代码涉及挂钩一些选择器/

$(document).ready(function () {
Configuration.anchorToUseForMainSearch = $("#header_element")
}

此选择器返回"length: 0",因为 DOM 尚未加载, 我应该使用其他事件吗?

尝试使用这个:

angular.element(document).ready(function () {
// Your document is ready, place your code here
});

但结果是一样的..

您可以为此创建一个指令并设置执行代码的超时。

我想说,你在这里走错了路。Angular 方式将避免使用 jQuery。如果你绝对必须,我建议你把它放在附加到主模块的.run((中。我希望文档在此函数触发时"准备就绪"。

angular.module('myApp', [])
.run(function myAppRunFn() {
// commit sins here. 
});

记录在这里: https://docs.angularjs.org/guide/module

var target = $("#wrapperDiv")[0]; //or document.body when you not sure

// create an observer instance
var observer = new MutationObserver(function(mutations) {
mutations.forEach(function(mutation) {
if($(mutation.addedNodes).filter('#header_element').length) {
//code for what you want here
console.log("Item added to DOM");
}  
});   
});
// configuration of the observer:
var config = { attributes: true, childList: true, characterData: true, subtree: true };

// pass in the target node, as well as the observer options
observer.observe(target, config);
setTimeout(function(){
console.log('Adding Element from some other code');
$("#innerDiv").append("<div id='header_element'>");
}, 2000);
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="wrapperDiv">
<div id="innerDiv">

</div>
<div>

最新更新