【问题标题】:angularJS ES6 DirectiveangularJS ES6 指令
【发布时间】:2017-05-24 14:51:38
【问题描述】:

我正在尝试在 angular es6 中开发应用程序。我有directve的问题。 这是我的代码

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实现

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

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

【问题讨论】:

  • 你也可以参考this answer
  • 使用 ES5 会遇到完全相同的问题。而且这个指令一开始就拥有一个控制器和一个隔离的范围是没有意义的。

标签: angularjs angularjs-directive ecmascript-6


【解决方案1】:

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

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

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

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

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

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

【讨论】:

  • 谢谢你拯救了我的一天。实际上我正在使用 bindtocontroller,所以它有它自己的范围对吗?不是全局范围。
  • 您正在使用隔离范围(通过在指令scope 定义中使用对象来定义)。 bindToController 是另外一回事 - 这基本上告诉 angular 使用控制器对象而不是 $scope 对象 - 但无论哪种方式它都会被隔离
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2017-08-08
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多