【问题标题】:calling an angular controller method via ng-click in es6在 es6 中通过 ng-click 调用角度控制器方法
【发布时间】:2018-03-21 05:15:14
【问题描述】:

我在 gulp 中使用 browserify 和 babelify 使用 es6 和 angular 1.6 进行测试,我注意到当我使用 es6 类创建控制器时,我不能再使用 ng-click 在 dom 上调用控制器的方法。

控制者:

    export default class FocusbtnsController {
    constructor($scope) {}

    testMethod() {
        alert('test method works!!');
    }
}

主模块:

import angular from 'angular';
import FocusbtnsController from './focusbtns.controller';

export default angular.module('shapesite', [])
    .controller('FocusbtnsController', FocusbtnsController);

HTML:

<div class="center-btns ng-scope" ng-controller="FocusbtnsController">
    <div class="focus-btn-container" style="left:50%;top:5%" ng-click="testMethod()">
        <div class="diamond">
            <div class="diamond-btn"></div>
        </div>
    </div>
</div>

我尝试从angular.module 中删除export default,但没有任何效果。 当我将方法 testMethod 添加到 $scope 参数 $scope.testMethod = testMethod; 时,它可以工作,但这样做感觉非常肮脏。

我错过了一些允许我在使用 es6 语法时调用控制器方法而无需将其分配给 $scope 的东西?

【问题讨论】:

  • 如果你要使用 1.5+,我建议你使用组件,它允许你在组件定义中为视图声明控制器,你可以使用 $ctrl 调用它的方法。

标签: javascript angularjs ecmascript-6 es6-class angular-controller


【解决方案1】:

为了扩展我的评论,一个简单的 Angular 1.5+ 组件看起来像这样。

mycomponent.component.html

<button ng-click="$ctrl.someMethod()">Click Me</button>

mycomponent.component.js

import template from './mycomponent.component.html';

class MyComponentController {
  constructor($filter) {
    'ngInject';

    this.$filter = filter;
  }

  someMethod() {
   console.log('Hello World');
  }
}

const myComponent = {
  template,
  controller: MyComponentController,
  bindings: {},
};
export default myComponent;

mycomponent.module.js

import myComponent from './mycomponent.component';

angular.module('MyModule')
  .component('myComponent', myComponent);

要使用你可以拨打&lt;my-component&gt;&lt;/my-component&gt;

另一种选择是 Nicholas Tower 的回答,但同样,我认为如果您使用的是 1.5+,只需使用组件即可。

【讨论】:

    【解决方案2】:

    如果您想使用类作为控制器(或具有原型继承的 ES5 对象),那么您需要使用控制器作为语法。这告诉 Angular 使用控制器本身上的变量,而不是 $scope 上的变量。所以你的模板会变成这样:

    <div class="center-btns ng-scope" ng-controller="FocusbtnsController as $ctrl">
        <div class="focus-btn-container" style="left:50%;top:5%" ng-click="$ctrl.testMethod()">
            <div class="diamond">
                <div class="diamond-btn"></div>
            </div>
        </div>
    </div>
    

    我建议更进一步,使用 angularJS 的组件,而不是 ng-controller。有关组件的示例,请参见 Baruch 的回答。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2023-03-24
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多