我有一个简单的指令,绘制了一些元素,就像这个例子。我想以编程方式设置一些样式属性,但在链接功能中,元素显然还没有。如何在将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