【问题标题】:Angular 1.5.6, $postLink and typescriptAngular 1.5.6、$postLink 和打字稿
【发布时间】:2016-10-05 01:36:06
【问题描述】:

我试图在我的指令中使用 $postLink(使用 typescript 和 ng 1.5.6)不幸的是,我真的不明白在哪里使用它。 它应该是指令类主体中名为“$postLink”的公共函数吗?

以下内容不起作用:

public $postLink(scope: ng.IScope , element: ng.IAugmentedJQuery, attrs: ng.IAttributes):void {

}

【问题讨论】:

    标签: angularjs hook typescript1.8


    【解决方案1】:

    这就是我使用 typescript 让它工作的方式(这个种子,确切地说:https://github.com/b091/ts-skeleton):

    import {directive} from "../../../decorators/directive";
    
    @directive()
    export class MyDirective implements ng.IDirective {
        public restrict: string = "A";
    
        public link: ng.IDirectivePrePost = {
            pre: ($scope: ng.IScope, element: ng.IAugmentedJQuery, attrs: ng.IAttributes): void => {
                console.log("pre() being called");
            },
            post: ($scope: ng.IScope, element: ng.IAugmentedJQuery, attrs: ng.IAttributes): void => {
                console.log("post() being called");
            }
        }
    }
    

    您可以在 angular 的类型文件中看到,IDirective 可以采用:

    interface IDirectivePrePost {
        pre?: IDirectiveLinkFn;
        post?: IDirectiveLinkFn;
    }
    

    interface IDirectiveLinkFn {
        (
            scope: IScope,
            instanceElement: IAugmentedJQuery,
            instanceAttributes: IAttributes,
            controller: {},
            transclude: ITranscludeFunction
        ): void
    }
    

    【讨论】:

      【解决方案2】:

      在你的组件控制器中应该是这样的:

      class MyCtrl {
        static $inject = ['$element'];
        // If you need the element for DOM manipulation,
        // then inject it as $element.
        // $scope can also be injected.
        constructor($element:ng.IAugmentedJQuery) {}
      
        // $postLink is different from a directive's link and doesn't have
        // arguments.
        public $postLink() {
           // The attrs can't be injected but instead you can define the
           // bindings of the component.
        }
      }
      

      【讨论】:

      • 我尝试的第一件事,不幸的是什么都没被解雇,我不知道为什么。
      • 是 angular.directive 还是 angular.component?
      • 这是一个指令
      • 它应该适用于组件和指令。您可以发布指令定义对象,也许那里有什么不同吗?
      猜你喜欢
      • 2018-04-15
      • 2016-05-01
      • 2019-02-23
      • 2016-03-10
      • 2017-05-02
      • 1970-01-01
      • 2019-06-20
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多