user3568783
user3568783

Reputation:

How can I access a scope function in a parent controller from a child controller when using Typescript?

I have a parent controller AppController for a DIV on my page and a child controller AdminHomeController that's in an area of the page inside that. Here is what I have defined so far.

interface AppControllerScope extends ng.IScope {
    app: AppController;
}

app.controller('appController', AppController);

class AppController {  
    static $inject = ['$scope',] 
    constructor( public $scope: AppControllerScope ) { 
        $scope.app = this; 
    }         
    doTask() = () => {
       var x = 99;
    } 
} 

class AdminHomeController {   
    static $inject = ['$scope']
    constructor(  public $scope: ?? ) { // << What should my interface look like?
        $scope.home = this;
        app.doTask();
    }
    app = $scope.app; // How can I set up a parameter of this controller
                      // that can be used on my web page or inside this
                      // controller?
}

Can someone tell me how I can access the parent controller function doTask() from inside the child controller and also on my page? I assume that somehow I have to set an interface here:

constructor(  public $scope: ?? ) {

But I am not sure what it should look like.

Upvotes: 3

Views: 2457

Answers (1)

basarat
basarat

Reputation: 275887

Here is the complete code:

/// <reference path="angular.d.ts" />

var app = angular.module('app', []);

interface AppControllerScope extends ng.IScope {
    app: AppController;
}

app.controller('appController', AppController);

class AppController {
    static $inject = ['$scope'];
    constructor(public $scope: AppControllerScope) {
        $scope.app = this;
    }
    doTask = () => {
        var x = 99;
    }
}

interface AdminHomeControllerScope extends AppControllerScope {
    home: AdminHomeController;
}

class AdminHomeController {

    public app: AppController;

    static $inject = ['$scope'];
    constructor(public $scope: AdminHomeControllerScope) { // << What should my interface look like?
        $scope.home = this;
        $scope.app.doTask();

        // For easier access if you want it
        this.app = $scope.app;
    }
}

There were a few code formatting (compile errors) in your code sample. I fixed those as well ^

Upvotes: 6

Related Questions