1

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.

2
  • You could refer this answer as well. Commented Jan 10, 2017 at 8:51
  • 1
    You would have the exact same problem using ES5. And it doesn't make sense for this directive to have a controller and an isolated scope in the first place. Commented Jan 10, 2017 at 9:24

1 Answer 1

3

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

Sign up to request clarification or add additional context in comments.

2 Comments

Thanks you saved my day.. Actually i am using bindtocontroller, so its had it's own scope right? not the global scope.
You are using isolated scope (defined by using an object in your directive scope definition). bindToController is something else - this basically tells angular to use the controller object instead of the $scope object - but it would have been isolated either way

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.