angularjsangularjs-controlleras

Get ControllerAs alias inside base controller in AngularJS


We have legacy code written in AngularJS that does not use controllerAs.

Sample Plunker

Our BaseController (Plunker: script.js line 19) has this code to make all class methods available in $scope without writing this.$scope.method = ...

this.$scope[key] = this[key].bind(this)

Now since we are starting to migrate to Controller as vm syntax we do not need this code any more. In Plunker NewCtrl does not even need $scope injected, but because of this line we need to.

Question: How to find out if current controller (NewCtrl) is used with controllerAs syntax or not?


Solution

  • If your app uses ui-router, you could use $state service to check if a controller is declared with as syntax.

    $state.get() returns a list of all registered states. Inside each item you can check for controllerAs existance or 'as' inside controller :

    controller: 'testCtrl as vm' or 
    controllerAs: 'vm'
    

    From inside a controller, you could use $state.current as above.