上面的答案雖然正確,但是是反模式。在大多數情況下,當你想修改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 –