2017-08-28 96 views
1

我试图运行的角度应用中的一些jQuery代码,我试图运行的代码涉及到勾上一些选择/运行jQuery代码

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

该选择返回“长度:0“,因为DOM尚未加载, 还有一些其他事件我应该使用?

尝试使用此:

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

但它是相同的结果..

+1

将所述元件'#header_element'将通过'角路线/部分loading'加载? –

+0

@Koushik Chatterjee。没有。 jquery代码将从外部项目运行,并挂接到角度应用程序 –

+0

澄清,你的意思是文档选择器? –

回答

0

您可以创建这样的指令,并设置超时执行代码。

+0

jquery代码将运行外部项目钩入角应用程序,所以我不能作为它的外部应用程序的指令。 正常document.ready假设工作? –

0

你会在这里走错了路,我会说。 Angular的方式可以避免使用jQuery。如果你绝对必须的话,我建议你把它放在你的主模块的.run()中。我希望文档能够在这个函数触发的时候“准备好”。

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

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

+0

jquery代码将从外部项目(不是角应用程序)中运行,并挂接到角度应用程序。所以我没有办法使用这个答案.. –

0

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>