1

I'm trying to use classes to define a directive. The html does show up and it does show it's calling the ctor and the controller functions. However, I have a class method that I want to call in the html from a ng-click but it's not getting called.

Note I'm working in 1.3x an can't upgrade at this time.

https://plnkr.co/edit/cWyyCahfoWWwk0UN49ep?p=preview

Directive:

class StoreHours{

  constructor(){
    console.log("inside ctor");
    this.restrict = 'E';
    this.templateUrl = 'storeHours.html';
    this.bindToController = true;
    this.controllerAs = 'vm';
    this.scope = {
      hours: '=',
      index: '=',
      addNewHour: '&'
    };
  }

  controller(){
    console.log("inside controller");
  }

  // the member metod that I want ng-click to call
  addNew(newHour){
    var vm = this;

    console.log("addNew()");

    vm.addNewHour({ hour: newHour, index: vm.index });

    vm.newHour = "";
  }

  // don't need this but just showing
  link(scope, element, attrs){

  }
}

app.directive('storeHours', () => new StoreHours);

HTML:

<div style="background-color: gray;">
  <h1>I'm the store hours component!</h1>

  <li ng-repeat="hrs in vm.hours">
    {{hrs}}
  </li>

  <input type="text" ng-model="vm.newHour" />
  <button ng-click="vm.addNew(vm.newHour)">Add New</button>
</div>

1 Answer 1

1

addNew() method is attached to the class scope, whether you need to attach it to the controller() scope (that is different)

Add the method inside the controller and you should be fine.

  controller(){
    console.log("inside controller");
    var vm = this;  
    vm.addNew = function(newHour){
      console.log("addNew()");
      vm.addNewHour({ hour: newHour, index: vm.index });
      vm.newHour = "";
    }
  }
Sign up to request clarification or add additional context in comments.

3 Comments

No other way around that huh? I don't enjoy that syntax but if there is no other way then that'll work.
Can I access the class methods from inside the controller so I can just set vm.addNew = ClassMethodFunction; so the function can be defined at the class level? Basically 'this' when in the ctor is different object than 'this' in controller() right? So how do I get 'this' of the ctor from inside the controller I guess?
i don't think it is possible, you should play with the scopes of the functions but it doesn't worth it. in my opinion is even clearer that your controller methods should be inside your controller, and doesn't mess with the directive scope.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.