簡體   English   中英

在angularJS應用程序文檔就緒事件中運行jQuery代碼

[英]Run jquery code in angularJS app document ready event

我試圖在angular應用程序中運行一些jquery代碼,我試圖運行的代碼涉及到鈎住一些選擇器/

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

由於尚未加載DOM,因此該選擇器返回“ length:0”,還有其他事件我應該使用嗎?

嘗試使用此:

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> 

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM