加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 综合聚焦 > 服务器 > 安全 > 正文

使用TypeScript和$inject机制定义AngularJS指令

发布时间:2020-12-17 08:40:51 所属栏目:安全 来源:网络整理
导读:最近我开始重构我正在使用TypeScript工作的Angular项目之一。使用TypeScript类定义控制器非常方便,并且对于缩小的JavaScript文件非常方便,这得益于static $ inject Array string属性。而且你得到相当干净的代码,而不从类定义分离Angular依赖: module app
最近我开始重构我正在使用TypeScript工作的Angular项目之一。使用TypeScript类定义控制器非常方便,并且对于缩小的JavaScript文件非常方便,这得益于static $ inject Array< string>属性。而且你得到相当干净的代码,而不从类定义分离Angular依赖:
module app {
  'use strict';
  export class AppCtrl {
    static $inject: Array < string > = ['$scope'];
    constructor(private $scope) {
      ...
    }
  }

  angular.module('myApp',[])
    .controller('AppCtrl',AppCtrl);
}

现在我正在寻找解决方案来处理类似的情况下的指令定义。我发现一个好的做法来定义指令作为函数:

module directives {

  export function myDirective(toaster): ng.IDirective {
    return {
      restrict: 'A',require: ['ngModel'],templateUrl: 'myDirective.html',replace: true,link: (scope: ng.IScope,element: ng.IAugmentedJQuery,attrs: ng.IAttributes,ctrls) => 
        //use of $location service
        ...
      }
    };
  }


  angular.module('directives',[])
    .directive('myDirective',['toaster',myDirective]);
}

在这种情况下,我不得不在指令定义中定义Angular依赖,如果定义和TypeScript类在不同的文件中,这可能非常容易出错。什么是用typescript和$ inject机制定义指令的最好方法,我正在寻找一个好的方法来实现TypeScript IDirectiveFactory接口,但是我不满意我发现的解决方案。

使用类和继承自ng.IDirective是使用TypeScript的方法:
class MyDirective implements ng.IDirective {
    restrict = 'A';
    require = 'ngModel';
    templateUrl = 'myDirective.html';
    replace = true;

    constructor(private $location: ng.ILocationService,private toaster: ToasterService) {
    }

    link = (scope: ng.IScope,ctrl: any) => {
        console.log(this.$location);
        console.log(this.toaster);
    }

    static factory(): ng.IDirectiveFactory {
        const directive = ($location: ng.ILocationService,toaster: ToasterService) => new MyDirective($location,toaster);
        directive.$inject = ['$location','toaster'];
        return directive;
    }
}

app.directive('mydirective',MyDirective.factory());

相关答案:http://stackoverflow.com/a/29223360/990356

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读