2012-12-12 196 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函數 - 它需要一個學生的參數,但硬編碼'約翰'?你可以在控制器內部而不是在方法中執行所需的操作嗎?例如,函數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擁有自己的函數來測試文檔。你可以做一個引導手冊,然後設置的用戶名:

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

對於這個工作,你需要從HTML中刪除NG-應用指令。

+18

你可以只是使用'$ document'而不是'angular.element(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:我知道這個問題很陳舊,但仍需要指出一些最佳實踐。 :)