angularJS ES6 指令

angularJS ES6 指令

问题描述:

我正在尝试使用 angular es6 开发应用程序.我的指令有问题.这是我的代码

I am trying to develop an application in angular es6 . I have a problem with directve. Here is my code

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()]);

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

The problem is i couldn't get the role value inside constructor. here is my html implementation

<a ui-sref="event" class="button text-uppercase button-md" role-permission="dfsd" detail="sdfdsfsfdssd">Create event</a>

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

If i console this it will get the controller object. But it will not get any result while use this.role.

好的,所以我设法找出这是如何工作的.

Ok, so I managed to find out how this works.

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

Basically, the scope values cannot be initialized on the controller's constructor (because this is the first thing executed on a new object) and there is also binding to be considered.

您可以在控制器中实现一个可以帮助您处理用例的钩子:$onInit:

There is a hook that you can implement in your controller that can help you with your use case: $onInit:

class RoleDirectiveController {
  constructor () { 
    // data not available yet on 'this' - they couldn't be
  }

  $onInit() {
    console.log(this.role)
  }
}

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

This should work. Note that this is angular1.5+ way of doing things when not relying on $scope to hold the model anymore. Because if you use the scope, you could have it in the controller's constructor (injected).