Search code examples
javascriptangularjsangularjs-scope

angular.element(..).scope() returns undefined initially


I am trying to access my angular controller's scope outside of the controller. I am using an external js library which performs certain actions and on completion executes certain callbacks. In one of the callbacks angular.element(document.findElementById('elementId').scope() returns undefined. But in the second callback that is executed after the first angular.element(document.findElementById('elementId').scope() returns the valid scope.

Here is some sample code

    <body id="authcontroller" ng-controller="AuthenticationController as auth">

<script>
    window.externalLibObj = {
     onCallback1: function(){
         // Undefined value for scope
         var scope = angular.element(document.getElementById('authcontroller')).scope();
     },
     onCallback2(): function(){
        // Valid value for scope
        var scope = angular.element(document.getElementById('authcontroller')).scope();
     }
    };
</script>
    </body>

The order in which these callbacks are executed are onCallback1 and then onCallback2. var scope is undefined in onCallback1 but has a value in onCallback2

Why is scope undefined in onCallback1?

Thank you for your help


Solution

  • It seems a timing issue. When your first callback is executed the scope isn't ready, but it is on your second callback. You should change your logic and trigger the callbacks within the controller when the associated view is correctly loaded.

    In your AuthenticationController add this:

    $scope.$on('$viewContentLoaded', function(){
      // here define/fire your callbacks and you will be sure that everything is init
    });
    

    I hope it helps