首页
学习
活动
专区
圈层
工具
发布
首页
学习
活动
专区
圈层
工具
MCP广场
社区首页 >问答首页 >Angularjs ES6类指令

Angularjs ES6类指令
EN

Stack Overflow用户
提问于 2018-04-17 17:07:30
回答 1查看 479关注 0票数 1

我试图使用类来定义指令。html确实会出现,并显示它正在调用ctor和控制器函数。但是,我有一个类方法,我想通过ng单击在html中调用它,但是它没有被调用。

注意:我在1.3xan中工作,现在无法升级。

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

指令:

代码语言:javascript
运行
复制
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:

代码语言:javascript
运行
复制
<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>
EN

回答 1

Stack Overflow用户

回答已采纳

发布于 2018-04-17 17:36:40

addNew()方法附加到类作用域,无论是否需要将它附加到controller()作用域(这是不同的)。

在控制器中添加该方法,您应该会没事的。

代码语言:javascript
运行
复制
  controller(){
    console.log("inside controller");
    var vm = this;  
    vm.addNew = function(newHour){
      console.log("addNew()");
      vm.addNewHour({ hour: newHour, index: vm.index });
      vm.newHour = "";
    }
  }
票数 1
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/49883780

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档