angularJS ES6指令

时间:2017-01-10 07:25:31

标签: angularjs angularjs-directive ecmascript-6

我正在尝试使用角度es6开发应用程序。我有直接问题。 这是我的代码

martin odersky

问题是我无法在构造函数中获得角色值。 这是我的html实现

export default class RoleDirective {
  constructor() {
    this.template="";
    this.restrict = 'A';
    this.scope = {
        role :"@rolePermission"
    };

    this.controller = RoleDirectiveController;
    this.controllerAs = 'ctrl';
    this.bindToController = true;
  }

  // Directive compile function
  compile(element,attrs,ctrl) {
        console.log("df",this)
  }

  // Directive link function
  link(scope,element,attrs,ctrl) {

        console.log("dsf",ctrl.role)
  }
}

// Directive's controller
class RoleDirectiveController {
  constructor () {
    console.log(this.role)
    //console.log("role", commonService.userModule().getUserPermission("change_corsmodel"));
    //$($element[0]).css('visibility', 'hidden');
  }

}

export default angular
  .module('common.directive', [])
  .directive('rolePermission',[() => new RoleDirective()]);

如果我控制它,它将获得控制器对象。但是在使用this.role时它不会得到任何结果。

1 个答案:

答案 0 :(得分:3)

好的,所以我设法找出了它是如何工作的。

基本上,范围值不能在控制器的构造函数上初始化(因为这是在新对象上执行的第一件事)并且还需要考虑绑定。

您可以在控制器中实现一个可以帮助您处理用例的挂钩:class RoleDirectiveController { constructor () { // data not available yet on 'this' - they couldn't be } $onInit() { console.log(this.role) } }

{{1}}

这应该有效。请注意,这是angular1.5 +处理方式,而不依赖于$ scope来保存模型。因为如果你使用范围,你可以在控制器的构造函数(注入)中使用它。

相关问题