正しい答えですが、アンチパターンです。ほとんどの場合、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関数を理解していません - それは学生の議論を取りますが、ハードコードの 'John'ですか?方法ではなく、コントローラの中で必要なものだけを行うことができますか?たとえば、関数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 –