不是具有共同范围的函数错误

时间:2015-10-21 06:18:31

标签: javascript angularjs typescript

我有以下代码作为我的控制器...

module scrumtool.app.Controllers {
    export class ConfigController implements Directives.IConfigScope{
        static $inject = [
            "$scope"
        ];
        public message: string = "Testing";
        constructor() { }

        clickMe = () => {
            return this.message;
        }
    }
}

暂时在指令模块下定义IConfigScope 接口 ...

export interface IConfigScope {
    message: string;
    clickMe(): string;
}

指令就像这样......

module scrumtool.app.Directives {
    export interface IConfigScope {
        message: string;
        clickMe(): string;
    }
    export class Cog implements ng.IDirective {
        restrict: string = "A";
        controller = Controllers.ConfigController;
        constructor($scope: Directives.IConfigScope) {

        }
        link = function($scope: Directives.IConfigScope, element: ng.IAugmentedJQuery, 
                        attr: ng.IAttributes, ctrl: Controllers.ConfigController) {
            element.on("click", (e) => {
                alert(ctrl.clickMe());
            });
        }

        static factory(): ng.IDirectiveFactory {
            var directive: ng.IDirectiveFactory =
                ($scope: Directives.IConfigScope) => new Cog($scope);

            directive.$inject = [];

            return directive;
        }
    }
}

基本上我能够做到这一点。我不明白的是,通过$scope变量,我可以访问 message 变量并让它提醒消息"测试"。

我能够理解的是为什么我不能简单地说:

alert($scope.clickMe());

让它返回消息。当我尝试上述内容时,我得到了未定义。

有人可以向我解释一下吗?

1 个答案:

答案 0 :(得分:3)

在:

中定义的依赖关系
static $inject = [
        "$scope"
    ];

必须以某种方式交付,注入。有角度的方式是通过 constructor 。所以我们需要这个:

// there is no param in constructor, to be used
// constructor() { }
// but we need one - $scope
constructor(protected $scope) { }

我们还应该提供一种传递的$ scope

constructor(protected $scope:IConfigScope) { }

这意味着,已通过的$scope将实施这些messagesclickMe

其他的话 - 控制器无法实现IConfigScope ,它将随之提供

但是如果我们想让控制器完成这项工作,我们应该使用controllerAs语法

export class Cog implements ng.IDirective {
    restrict: string = "A";
    controller = Controllers.ConfigController;
    controllerAs = "Ctrl";
    ...

以及以后视图模板中的任何地方我们都可以使用

 {{Ctrl.messages}}
 ...
 ng-click="Ctrl.clickMe()"