angularJS ES6 Directive

China☆狼群 提交于 2019-12-25 07:47:58

问题


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

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>

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


回答1:


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.

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)
  }
}

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).



来源:https://stackoverflow.com/questions/41563351/angularjs-es6-directive

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!