在使用Typescript时,如何从子控制器访问父控制器中的作用域函数?

时间:2014-07-26 12:35:47

标签: javascript angularjs typescript

我的页面上有DIV的父控制器AppController和内部页面区域中的子控件AdminHomeController。这是我到目前为止所定义的内容。

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?
}

有人能告诉我如何从子控制器内部以及我的页面上访问父控制器函数doTask()吗?我假设我必须在这里设置一个接口:

constructor(  public $scope: ?? ) {

但我不确定它应该是什么样的。

1 个答案:

答案 0 :(得分:6)

以下是完整的代码:

/// <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;
    }
}

代码示例中有一些代码格式(编译错误)。我也修好了那些^