rongmei
rongmei

Reputation: 33

this.$scope is null in $postLink() of controller

class pageController {

    constructor($scope, MyEditableGrid) {
        this.$scope = $scope;
        this.MyEditableGrid = MyEditableGrid;
        this.myEditableGrid = {
            appScope: this.$scope,
            .....
        }
    }
    $postLink() {
        this.$scope.$on('message', function (event, data) {
            console.log(this.MyEditableGrid); ==> null?
            console.log(this.$scope);  ==> null?
            console.log(this.myEditableGrid); ==> null
        }
    }  
}

The message was broadcast from service.js:

$rootScope.$broadcast('message',data);

the error message in browser inspector for console.log(this.MyEditableGrid):

TypeError: Cannot read property 'MyEditableGrid' of null

The error message in browser inspector for console.log(this.$scope):

TypeError: Cannot read property '$scope' of null

Upvotes: 0

Views: 128

Answers (1)

Martin
Martin

Reputation: 16300

In your constructor you made EditableGrid a property of your class, not the $scope.

You can with access it with this.EditableGrid, or add it to the $scope in the constructor.

--UPDATE AFTER QUESTION CODE HAS BEEN UPDATED--

You are losing the scope of this by using function(..) rather than the fat arrow function which preserves the scope of this.

Try this:

this.$scope.$on('message', (event, data) => { 
  // this still points to the class instance
}):

Upvotes: 0

Related Questions