Search code examples
angularjstypescriptangularjs-scope

Typescript/AngularJS: $scope undefined outside of constructor


How come I don't have scope for $scope outside of the constructor, unless I define my function using the fat arrow? Or is it possible to access $scope without defining a function using fat arrow?

namespace FooBar {
    export interface MyScope extends ng.IScope {
        message: string;
    }

    export class SandboxCtrl {
        static $inject = ["$scope", "$timeout"];
        private scope: MyScope;
        private timeout: ITimeoutService;
        constructor($scope: MyScope, $timeout: ng.ITimeoutService) {
            this.scope = $scope;
            this.timeout = $timeout;
            timeout(this.foo, 1000); // does not work
            timeout(this.bar, 1000); // works
        }

        public foo() {
            this.scope.message = "foo bar"; // does not work
        }

        bar = () => {
            this.scope.message = "foo bar"; // works
        }
    }
}

UPDATE I noticed I didn't shared the entire problem as I didn't knew it was because $timeout directive which causes the problem. Anyhow I updated my example.


Solution

  • Without going into much details the problem is solved by using bind to bind this to the function.

    timeout(this.foo.bind(this), 1000);