上面的答案虽然正确,但却是反模式。在大多数情况下,当您想要修改 DOM 或等待 DOM 加载然后做一些事情(准备好文档)时,您不是在控制器中而是在链接函数中进行。
angular.module('myModule').directive('someDirective', function() {
return {
restrict: 'E',
scope: {
something: '='
},
templateUrl: 'stuff.html',
controller: function($scope, MyService, OtherStuff) {
// stuff to be done before the DOM loads as in data computation, model initialisation...
},
link: function (scope, element, attributes)
// stuff that needs to be done when the DOM loads
// the parameter element of the link function is the directive's jqlite wraped element
// you can do stuff like element.addClass('myClass');
// WARNING: link function arguments are not dependency injections, they are just arguments and thus need to be given in a specific order: first scope, then element etc.
}
};
});
老实说,$document 或 angular.element 的有效使用极为罕见(无法使用指令而不仅仅是控制器),并且在大多数情况下,您最好审查您的设计。
PS:我知道这个问题很老,但仍然必须指出一些最佳实践。:)