Search code examples
angularjsangular-ui-router

AngularJs : does ui-router *require* me to inject $scope into my controller (even with Controller As syntax)?


One of the advantages of the "Controller As" syntax is that it frees us from $scope.

BUT, I am having problems which seem to indicate that ui-router requires $scope - probably to access the state.

There are multiple similar questions, not with a satisfactory answer, so I am looking for a canonical answer, which I can refer those other questions to.

  1. does ui-router require me to inject $scope into my controller, even if the controller code never references $scope (because I am using "controller as" syntax)? (the answer to Angular ui router controlleras syntax not working seems to imply that it does. Also, removing the injection of $scope into this working Plunker breaks it)

  2. can I avoid that (possibly by telling my ui-router config to get the state from the controller of the "controller as" declaration)?


Solution

  • Maybe the following code could be useful.

    var myApp = angular.module('helloworld', ['ui.router'])
    .config(function($stateProvider) {
      var helloState = {
        name: 'hello',
        url: '/hello',
        template: '<h3>hello world!</h3>'
      }
      
      class AboutStateController {
        constructor() {
          this.name = 'John Dow';
        }
      }
     
      var aboutState = {
        name: 'about',
        url: '/about',
        template: '<h3>Hello <span>{{aboutStateController.name}}</span></h3>',
        controller: AboutStateController,
        controllerAs: 'aboutStateController'
      }
    
      $stateProvider.state(helloState);
      $stateProvider.state(aboutState);
    });
    
    angular.bootstrap(document.body, ['helloworld']);
    <script src="https://cdnjs.cloudflare.com/ajax/libs/angular.js/1.7.5/angular.min.js"></script>
    <script src="//unpkg.com/@uirouter/angularjs/release/angular-ui-router.min.js"></script>
    
        <a ui-sref="hello" ui-sref-active="active">Hello</a>
        <a ui-sref="about" ui-sref-active="active">About</a>
    
        <ui-view></ui-view>