2017-08-28 114 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>