2012-12-12 15 views
28

javascript関数から角度関数を呼び出す方法はありますか?文書の準備角度関数を呼び出す

function AngularCtrl($scope) { 
    $scope.setUserName = function(student){ 
    $scope.user_name = 'John'; 
    } 
} 

私は私のhtmlで以下の機能が必要になります。

jQuery(document).ready(function(){ 
    AngularCtrl.setUserName(); 
} 

問題はこちらのページがロードされているので、HTMLでNGディレクティブがコンパイルされていないとき、私のHTMLコードが存在しています。だから私はしたい$ compile(jQuery( "PopupID")); DOMがロードされたとき。

ドキュメント上で角度関数を呼び出す方法はありますか?誰もがこれで私を助けることができますか?

+0

私はあなたの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 –

答えて

45

Angularには、ドキュメントの準備ができているかどうかをテストする独自の機能があります。あなたは手動でブートストラップを行い、その後、ユーザー名を設定することができます:あなたは、HTMLからNG-アプリディレクティブを削除する必要があり、この作業では

angular.element(document).ready(function() { 
    var $injector = angular.bootstrap(document, ['myApp']); 
    var $controller = $injector.get('$controller'); 
    var AngularCtrl = $controller('AngularCtrl'); 
    AngularCtrl.setUserName(); 
}); 

を。

+18

'angle.element(document)'の代わりに '$ document'を使います。 [docs](http://code.angularjs.org/1.1.5/docs/api/ng.$document)を確認してください。最初に注入する必要があることに注意してください。 –

2

正しい答えですが、アンチパターンです。ほとんどの場合、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:この質問は古いですが、まだいくつかのベストプラクティスを指摘していたことがわかります。 :)

関連する問題