Nic Strong
Nic Strong

Reputation: 6592

Call Angular controller from script onload

I am trying to update the state of my controller after loading of a script from onload callback.

I load the Google Client API:

<script src="https://apis.google.com/js/client.js?onload=OnLoadCallback"></script>

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;          
};

It cannot seem to create a controller with the $scope injected. As the call $controller('UserCtrl') fails with:

Uncaught Error: Unknown provider: $scopeProvider <- $scope

You can see the error by viewing the console in this Plunk.

Upvotes: 3

Views: 5276

Answers (1)

Arun P Johny
Arun P Johny

Reputation: 388316

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; 
  })
}

Demo: 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')

Demo: Plunker

Upvotes: 5

Related Questions