11

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

5
  • What exactly isn't clear about the error? This might help: stackoverflow.com/a/29641308/218196 Commented Oct 21, 2015 at 23:01
  • 2
    It is unclear why this error appear and how to fix it. My example is the same as in solution you linked. Commented Oct 21, 2015 at 23:15
  • 1
    may be related to this issue github.com/angular/angular.js/issues/12597 Commented Oct 21, 2015 at 23:27
  • @klode, well I was trying to use also services in this way and got same error Commented Oct 21, 2015 at 23:32
  • The solution to your problem is in that issue also. it looks like they broke it in 1.3 for performance reasons (the answer that @FelixKling cites is obviously refers to older Angular version, 1.2.x). Commented Oct 22, 2015 at 6:53

2 Answers 2

2
'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.

Sign up to request clarification or add additional context in comments.

1 Comment

This is not at all the recommended way to work with things (don't assign directly to $scope) nor the documented way (controllers should be able to be classes since they're newed up)
0

This seems to work:

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

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.