Angularjs ES6类指令

时间:2018-04-17 17:07:31

标签: javascript angularjs

我正在尝试使用类来定义指令。 html确实显示,它确实显示它正在调用ctor和控制器功能。但是,我有一个类方法,我想通过ng-click在html中调用,但它没有被调用。

注意我在1.3x工作,此时无法升级。

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

指令:

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 个答案:

答案 0 :(得分:1)

addNew()方法附加到类范围,无论是否需要将其附加到controller()范围(不同)

在控制器中添加方法,你应该没问题。

  controller(){
    console.log("inside controller");
    var vm = this;  
    vm.addNew = function(newHour){
      console.log("addNew()");
      vm.addNewHour({ hour: newHour, index: vm.index });
      vm.newHour = "";
    }
  }