2012-12-12 205 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:我知道这个问题很陈旧,但仍需要指出一些最佳实践。 :)