簡體   English   中英

querySelectorAll不適用於ngInclude,uiView

[英]querySelectorAll doesn't work with ngInclude, uiView

我想獲取一個元素內的所有<img>元素。 為此,我創建了一個指令“ find-images”:

app.directive('findImages', function() {
    return {
        restrict: 'A',
        scope: {},
        link: function(scope, element, attrs) {
            var img_elements = element[0].querySelectorAll('img');
            console.log(img_elements) //doesn't have img elements nested inside ngInclude, uiView
        }
    }
})

我在body標簽中使用了此指令,如下所示:

<body find-images>

但是,我正在使用ui-router並且在許多地方都使用ng-include (以加載嵌套的部分)。 我面臨的問題是querySelectorAll不返回嵌套在ng-includeui-view img元素 如何獲得嵌套在其中的元素? 另外,所有嵌套元素(ui-view,ng-include)都在body標簽內。

問題是,ng-include將在指令的鏈接功能之后包含元素。 這將取決於應用程序的結構以及您要實現的目標,但是從本質上(通過超時,承諾或回調),您需要一種機制來確定DOM何時處於穩定狀態(ng- include可能有更多ng-includes等,可能會變得復雜),然后在那之后運行指令邏輯。

在ui-router中觸發的statechangesuccess事件中實現邏輯,您可以將其視為與頁面加載相同。

angular.module('app', [])
.run(['$document', function ($document) {

 $rootScope.$on("$stateChangeSuccess", function (event, toState, toParams, fromState, fromParams) {
     var body = $document.getElementsByTagName("body")[0];
     var img_elements = element[body].querySelectorAll('img');
 }

});

更新

另一種選擇是在渲染完成后使用ng-include引發的onload事件。

同樣不要忘記nginclude本身就是指令,可以在許多實例中使用ngswitch而不是nginclude和render自定義指令。

這樣,您的控制器中的邏輯就更少了,而在視圖中什么時候呈現的則更加明顯。

暫無
暫無

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

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