Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Using ES6 Classes as Angular 1.x directives

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?

like image 647
Boughtmanatee Avatar asked Feb 20 '15 01:02

Boughtmanatee


2 Answers

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)

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.

like image 75
michal.chochol Avatar answered Nov 15 '22 22:11

michal.chochol


As mentioned in a comment, the module.directive() method expects a factory function rather than a constructor.

The most simple way would be to wrap your class in a function that returns an instance:

angular.module('app')
    .directive('dateBlock', () => new DateBlock());

However, this will only work in the most limited sense - it does not allow for dependency injection and the compile and link functions of your directive (if defined) will not work as expected.

In fact, this is a problem I have looked into quite extensively and it turned out to be fairly tricky to solve (for me at least).

I wrote an extensive article covering my solution, but as far as you are concerned I can point you to the discussion of the two main issues that need to be resolved:

  1. Dynamically converting a class definition into an angular-compatible factory function

  2. Allowing a directive's link and compile functions to be defined as class methods

The full solution involves too much code to paste here, I think, but I have put together a working demo project which allows you to define a directive as an ES6 class like this:

class MyDirective {
    /*@ngInject*/
    constructor($interval) {
        this.template = '<div>I\'m a directive!</div>';
        this.restrict = 'E';
        this.scope = {}
        // etc. for the usual config options

        // allows us to use the injected dependencies
        // elsewhere in the directive (e.g. compile or link function)
        this.$interval = $interval;
    }

    // optional compile function
    compile(tElement) {
        tElement.css('position', 'absolute');
    }

    // optional link function
    link(scope, element) {
        this.$interval(() => this.move(element), 1000);
    }

    move(element) {
        element.css('left', (Math.random() * 500) + 'px');
        element.css('top', (Math.random() * 500) + 'px');
    }
}

// `register` is a helper method that hides all the complex magic that is needed to make this work.
register('app').directive('myDirective', MyDirective);

Check out the demo repo here and here is the code behind register.directive()

like image 48
Michael Bromley Avatar answered Nov 15 '22 20:11

Michael Bromley