在文档就绪时调用 AngularJS 函数 [英] Call AngularJS function on document ready

查看:29
本文介绍了在文档就绪时调用 AngularJS 函数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

有没有办法从 JavaScript 函数调用 Angular 函数?

Is there a way to call an Angular function from a JavaScript function?

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

我的 HTML 中需要以下功能:

I need the following functionality in my HTML:

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

这里的问题是我的 HTML 代码在加载页面时存在,因此未编译 html 中的 ng 指令.所以我想在加载DOM时$compile(jQuery("PopupID"));.

The problem here is my HTML code is present when page is loaded and hence the ng directives in the html are not compiled. So I would like to $compile(jQuery("PopupID")); when the DOM is loaded.

有没有办法在文档准备好时调用 Angular 函数?

Is there a way to call a Angular function on document ready?

推荐答案

Angular 有自己的功能来测试文档就绪.您可以进行手动引导,然后设置用户名:

Angular has its own function to test on document ready. You could do a manual bootstrap and then set the username:

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

为此,您需要从 html 中删除 ng-app 指令.

For this to work you need to remove the ng-app directive from the html.

这篇关于在文档就绪时调用 AngularJS 函数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆