AngularJS指令模型符号与TypeScript接口



当使用强类型接口时,如何初始化AngularJS指令的隔离作用域?如果您想使用模型接口以及"@""=""&"绑定符号,那么您可能会混淆编译器,因为您无法将字符串变量分配给具有不兼容类型的属性。

例如:

module widgets {
    'use strict';
    export interface IWidget extends ng.IScope {
        removed: boolean;
        onChanged: ()=>void;
        description: string;
        toggle:()=>void;
    }
    export class Widget implements ng.IDirective {
        public templateUrl = 'app/widgets/widget.html';
        public restrict = 'E';
        public scope: IWidget = {
            removed: "@",
            onChanged: "&",
            description: "="
        };
        public link: (scope: IWidget, element: ng.IAugmentedJQuery, 
                      attrs: ng.IAttributes) => void;
        static factory(): any {
            /* @ngInject */
            var directive = () => {
                return new Widget();
            };
            return directive;
        }
        constructor() {
            this.link = (scope: IWidget, element: ng.IAugmentedJQuery, 
                         attrs: ng.IAttributes) => {
                var init = () => {
                    scope.toggle = this._toggle.bind(this);
                    scope.$on('$destroy', this.destruct);
                    scope.$apply();
                };
                element.ready(init);
            };
        }
        private _toggle() {
            // updated: this throws the type error
            this.scope.removed = !this.scope.removed;
        }
        private destruct() {    
        }
    }
}

给定上面的代码,请注意onChanged将产生编译器错误,因为您不能将字符串"&"分配给函数。

您可能会得到以下错误:2349 Cannot invoke an expression whose type lacks a call signature.

或者removed属性上出现此错误:2322 Type 'boolean' is not assignable to type 'string'.

事实上,即使您对模型使用any,编译器仍然不允许您在定义属性后更改其基本类型。

有什么办法解决这个问题吗?

您可能会收到以下错误:2349无法调用类型缺少调用签名的表达式。

主要原因是scope成员需要字符串链接(这也是我不再是角度倡导者的原因之一)。

成员onChanged应该是可调用的,例如:

    public scope: IWidget = {
        removed: "@",
        onChanged: "&",
        description: "="
    };
    public link: (scope: IWidget, element: ng.IAugmentedJQuery, attrs: ng.IAttributes) => void {
            scope.onChanged(); // WILL WORK FINE
    }

您可能滥用了代码中的注释IWidget(问题未提供)。

这里的问题是指令定义。

它希望范围是IDictionary<string, string>,但类型any也可以:

export class Widget implements ng.IDirective {
    public templateUrl = 'app/widgets/widget.html';
    public restrict = 'E';
    //public scope: IWidget = {
    public scope: any = {
        removed: "@",
        onChanged: "&",
        description: "="
    };

在指令定义中,这里的scope是关于描述如何处理html属性(作为valuefunction…传递)。它的类型不是IWidget。当作用域实例传递给controllerlink 时,类型IWidget将发挥作用

如上所述,IDictionary也将工作:

public scope: {[key: string] : string} = {
//public scope: any = {
    "removed": "@",
    "onChanged": "&",
    "description": "="
};

但是any : {...}和简化符号也会起到同样的作用。

最新更新