2015-04-02 59 views
0

我有一個簡單的指令,繪製了一些元素,就像這個例子。我想以編程方式設置一些樣式屬性,但在鏈接功能中,元素顯然還沒有。如何在將DOM元素添加到我的指令時得到通知?

Here's a fiddle.

我認爲正在發生的是,當我稱之爲colorSquares功能,沒有廣場尚未在DOM。將它包裝在$超時中,它可以工作,但這只是感覺錯誤。

當元素存在時,我可以通知任何方式嗎?或者是否有一個地方可以放置訪問它們的代碼,並保證在它們存在後運行?

myApp.directive('myDirective', ['$timeout', function ($timeout) { 
return { 
    restrict: 'E', 
    replace: false, 
    link: function (scope, elem, attr) { 

     scope.squares = [1,2,3,4,5]; 

     function colorSquares() { 
      var squaresFromDOM = document.getElementsByClassName('square'); 
      for (var i = 0; i < squaresFromDOM.length; i++) { 
       squaresFromDOM[i].style['background-color'] = '#44DD44'; 
      } 
     } 

     // this does not work, apparently because the squares are not in the DOM yet    
     colorSquares(); 

     // this works (usually). It always works if I give it a delay that is long enough.   
     //$timeout(colorSquares); 


    }, 
    template: '<div><div ng-repeat="s in squares" class="square"></div></div>' 
}; 

}]);

+0

我強烈推薦閱讀[本文](http://stackoverflow.com/questions/14994391/thinking-in-angularjs-if-i-have-a-jquery-background)。它會讓你的生活變得如此簡單。 – Pete 2015-04-02 20:23:09

回答

0

你應該使用Angular而不是使用Angular,也就是說你應該使用數據綁定來做你正在做的事情而不是事件/通知。

http://jsfiddle.net/efdwob3v/5/

link: function (scope, elem, attr) { 
    scope.squares = [1,2,3,4,5]; 
    scope.style = {"background-color": "red"}; 
}, 
template: '<div><div ng-repeat="s in squares" class="square" ng-style="style"></div></div>' 

那說,有在做上述,只是使用具有紅色背景色,甚至只是在做style="background-color: red;"

0

你把答案在你qeustion不同的類沒有區別, 「如果我給它足夠長的延遲,它總是有效的。」

所以,只要使延遲足夠長,在這種情況下可以通過添加一個onload事件來實現,因爲當元素被添加到DOM時,它會調用該事件。

因此,而不只是colorSquares();你可以使用:

window.addEventListener("load", colorSquares); 

雖然這可能不是理想的解決方案,因爲它也將觸發,當別的東西觸發onload事件。

0

直接回答你的問題。要知道一個元素是否被添加到指令或DOM中,您可以簡單地在該元素上添加一個指令,因爲指令只有在它所在的元素已經在DOM中時纔會運行。

使用你的代碼的一部分,作爲一個例子:

myApp.directive('myDirective', function() { 
    return { 
     ...  
     //put custom directive that will notify when DOM is ready 
     template: '<div><div ng-repeat-ready ng-repeat="s in squares" class="square"></div></div>' 
    }; 
}); 

這裏是習俗ng-repeat-ready指令:

myApp.directive('ngRepeatReady', function() { 
    return { 
     link: function (scope) { 
      if (scope.$last) { 
       //do notification stuff here 
       //for example $emit an event 
       scope.$emit('ng-repeat is ready'); 
      } 
     } 
    } 
}); 

這個指令時的元素是位於運行已經在DOM並檢查該元素是否在範圍上具有$last屬性(ng-repeat爲迭代對象的最後一個元素設置此標誌),這意味着ng-repeat指令已完成,您現在可以對其進行操作DOM安全。

相關問題