asp.nettypescriptangularjs-rootscope

Define rootscope variable in an .ASPX file


I am trying to define an AngularJS rootscope variable in a .ASPX file to use in a TypeScript file, but I am unsure of how to do this. I am open to any way to be able to define a value in an .ASPX file and use it in TypeScript, so any other suggestion will work for me.


Solution

  • If you simply need to tell TypeScript that the property is there, you can extend the rootScope interface:

    interface extendedRootScope extends ng.IRootScopeService {
        myProp: number;
    }
    

    Then when you inject $rootScope in your controller, type it as your new interface:

    export class MyController {
        constructor(private $rootScope: extendedRootScope) { }
    
        someMethod() {
            // Access this.$rootScope.myProp
        }
    }
    

    If you need to access $rootScope from outside the Angular world (like in your ASPX page) to add the property, you can do something like this:

    <script>
        var injector = angular.element('[ng-app]').injector();
        var $rootScope = injector.get('$rootScope');
    
        $rootScope.myProp = 1;
    </script>
    

    This assumes you are using ng-app to initialize your Angular app.

    Similarly, you could create an Angular service on the fly in a script tag, inject $rootScope into that service, and add properties to it.