ControllerAs不使用es6语法

时间:2017-07-09 13:03:51

标签: angularjs ecmascript-6

我通过以下设置在模板中收到正确的信息。但是当我尝试使用controllerAs语法并参考

{{ app.User }} 

{{ $ctrl.app.User }}

它不起作用。我使用ES6语法和一个转换器fyi。

此设置正常:

模板:

<div><h4>Current App Scope User: </h4> {{ $ctrl.User }}</div>

控制器:

class AppController {

  constructor($state, $rootScope, SessionService) {
    this.$state = $state;
    this.User = null;



    $rootScope.$on('UserIsUpdated', (event, user) => {
      this.User = user;
    });

    SessionService.retrieve();
  }

}
AppController.$inject = ['$state', '$rootScope', 'SessionService'];


export const app = {
  controller: AppController,
  controllerAs: app,
  templateUrl: 'app/main/parent/app.html'
}

1 个答案:

答案 0 :(得分:1)

以下是使用ES6类语法编写的AngularJS控制器的示例:

class AppController {

  constructor($scope) {
    this.$scope = $scope;
  };

  $onInit () {
    this.$scope.hello = "Hello, ";
    this.world = "world"
  }

}

AppController.$inject = ['$scope'];

angular.module("app",[])
.controller("AppController", AppController)
<script src="//unpkg.com/angular/angular.js"></script>
  <body ng-app="app" ng-controller="AppController as $ctrl">
    <h1>ES6 AngularJS</h1>
    <p>{{hello}} {{$ctrl.world}}</p>
  </body>

另见ToddMoto: AngularJS styleguide (ES2015)