SET001
SET001

Reputation: 11718

error when using ES6 classes with angular services/controllers

I want to use ES6 classes in Angular application and trying to use it like this:

'use strict';

class EditorCtrl{
    constructor(){
        this.something = "ASd";
    }
    foo(){

    }
}
angular.module('Editor').controller('EditorCtrl', EditorCtrl);

but for some reason this code give me an error: Class constructors cannot be invoked without 'new'. Why is this happens and how I can fix this?

Angular: 1.4.7 Chrome: 46.0.2490.71

Upvotes: 11

Views: 1927

Answers (2)

Damjan Pavlica
Damjan Pavlica

Reputation: 33963

This seems to work:

angular
  .module('Editor')
  .controller('EditorCtrl', () => new EditorCtrl())

Upvotes: 0

pcdoneright.com
pcdoneright.com

Reputation: 37

'use strict';

class EditorCtrl{
    constructor($scope){
        this.something = "ASd";
    }
    foo(){

    }
}
// Use this instead.
angular.module('Editor').controller('EditorCtrl', ['$scope', function($scope) {
    return new EditorCtrl($scope);
}]);

As the error informs must return 'new'. This way injection will also work. Cheers.

Upvotes: 2

Related Questions