从脚本加载调用 Angular 控制器 [英] Call Angular controller from script onload
问题描述
我正在尝试从 onload 回调加载脚本后更新控制器的状态.
I am trying to update the state of my controller after loading of a script from onload callback.
我加载了 Google 客户端 API:
I load the Google Client API:
<script src="https://apis.google.com/js/client.js?onload=OnLoadCallback"></script>
然后在 OnLoadCallback 中,我尝试手动引导 AngularJS 并将设置状态设置到我的控制器上:
Then in OnLoadCallback I try to manually bootstrap AngularJS and set the set state on to my controller:
function OnLoadCallback() {
var $injector = angular.bootstrap(document, ['app']);
// load required gapi APIs
var $controller = $injector.get('$controller');
var UserCtrl = $controller('UserCtrl');
UserCtrl.user.apiLoaded = true;
};
它似乎无法创建注入 $scope 的控制器.由于调用 $controller('UserCtrl')
失败:
It cannot seem to create a controller with the $scope injected. As the call $controller('UserCtrl')
fails with:
未捕获的错误:未知提供者:$scopeProvider <- $scope
Uncaught Error: Unknown provider: $scopeProvider <- $scope
您可以通过查看此 Plunk 中的控制台来查看错误.
You can see the error by viewing the console in this Plunk.
推荐答案
你的controller用法不对,必须在controller范围内设置值
Your usage of controller is wrong, the value has to be set in the scope of the controller
function OnLoadCallback() {
//gapi.client.setApiKey('XXXXXXXXXXXX');
//gapi.client.load('drive', 'v2', function() {
var $injector = angular.bootstrap(document, ['app']);
console.log('Angualar bootstrap complete');
var $scope = angular.element('body').scope();
console.log('Find scope', $scope)
$scope.$apply(function(){
$scope.user.apiLoaded = true;
})
}
演示:Plunker
如果要获取控制器实例,则必须手动传递预期的注入值
If you want to get the controller instance, then you will have to manually pass the expected injected values
var $controller = $injector.get('$controller');
var UserCtrl = $controller('UserCtrl', {
$scope: $scope
});
console.log(UserCtrl, 'UserCtrl')
演示:Plunker
这篇关于从脚本加载调用 Angular 控制器的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!