使用 ES6 类作为 Angular 1.x 指令 [英] Using ES6 Classes as Angular 1.x directives

查看:19
本文介绍了使用 ES6 类作为 Angular 1.x 指令的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在做一个小项目来玩转 ES6 带来的好东西,我试图将注册一个类设置为 angular 指令,但我遇到了这个错误类型错误:无法调用类作为一个函数",但从示例中我发现他们只是编写类并将其注册为 angular 作为指令.这是我的指令.

I'm doing a small project to play around the goody bag the ES6 is bringing, I'm trying to set register a class as an angular directive, but I'm running into this error "TypeError: Cannot call a class as a function", but from the examples I'm finding they just write the class and register it with angular as a directive. Here's my directive.

class dateBlock {
  constructor () {
    this.template = '/app/dateblock/dateblock.html';
    this.restrict = 'AE';
    this.scope = {};
  }
};

export default dateBlock

以及我在其中导入并声明它的索引.

and my index where I import it and then declare it.

import calendarController from './calendar/calendar.js'
import dateBlock from './dateblock/dateblock.js'

function setup($stateProvider) {
    $stateProvider
      .state('base', {
        url: '',
        controller: calendarController,
        templateUrl: '/app/calendar/calendar.html'
      });
    };

setup.$inject = ['$stateProvider']

var app = angular.module('calApp',['ngAnimate','ui.router','hmTouchEvents', 'templates'])
  .config(setup)
  .controller('calendarController', calendarController)
  .directive('dateBlock', dateBlock)

如果我错过了一些关键步骤,我很乐意听到.另外一个附带问题是将所有应用程序组件导入索引并在那里注册它们还是导出应用程序并在组件内导入和注册更干净?

If I missed some crucial step I'd love to hear it. Also side question is it cleaner to import all the apps components to the index and register them all there or export the app and import and register within the components?

推荐答案

在我看来,没有必要使用像 register.js 这样的外部库,因为您可以通过这种方式将指令创建为 ES6 类:

From my point of view, there is no need to use external libraries like register.js, because you can create directive as a ES6 class in this way:

class MessagesDirective {
    constructor() {
        this.restrict = 'E'
        this.templateUrl = 'messages.html'
        this.scope = {}
    }

    controller($scope, $state, MessagesService) {
        $scope.state = $state;
        $scope.service = MessagesService;
    }

    link(scope, element, attrs) {
        console.log('state', scope.state)
        console.log('service', scope.service)
    }
}
angular.module('messages').directive('messagesWidget', () => new MessagesDirective)

使用指令控制器允许您注入依赖项,即使没有额外的声明(例如 MessagesDirective.$inject = ['$scope', '$state', 'MessagesService']),所以你如果需要,可以通过范围使用链接功能中的服务.

Using directive controller allows you to inject dependencies, even without additional declaration (ex. MessagesDirective.$inject = ['$scope', '$state', 'MessagesService']), so you can use services in link function via scope if you need.

这篇关于使用 ES6 类作为 Angular 1.x 指令的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆