上面的答案虽然正确,但是是反模式。在大多数情况下,当你想修改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.
}
};
});
在所有诚实,$文档或angular.element的有效使用是非常罕见的(无法使用的指令,而不是只是一个控制器),并在你查看你的设计更好的大多数情况下。 PS:我知道这个问题很陈旧,但仍需要指出一些最佳实践。 :)
我不明白你的setUserName函数 - 它需要一个学生的参数,但硬编码'约翰'?你可以在控制器内部而不是在方法中执行所需的操作吗?例如,函数MyCtrl($ scope){$ scope.user_name ='John'; ...}。或者是为时已晚?也许$ viewContentLoaded会帮助,如果你使用ng-view:http://stackoverflow.com/questions/11454383/angularjs-targeting-elements-inside-an-ng-repeat-loop-on-document-ready –