我有一個簡單的指令,繪製了一些元素,就像這個例子。我想以編程方式設置一些樣式屬性,但在鏈接功能中,元素顯然還沒有。如何在將DOM元素添加到我的指令時得到通知?
我認爲正在發生的是,當我稱之爲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>'
};
}]);
我強烈推薦閱讀[本文](http://stackoverflow.com/questions/14994391/thinking-in-angularjs-if-i-have-a-jquery-background)。它會讓你的生活變得如此簡單。 – Pete 2015-04-02 20:23:09