0

我正在測試使用角度爲1.6的es6使用browserify和babelify在吞嚥,我注意到當我使用es6類創建控制器時,我無法再調用控制器使用ng-click的方法。通過ng-click調用角度控制器方法es6

控制器:

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的,但沒有效果。 當我將方法testMethod添加到$scope參數$scope.testMethod = testMethod;它可以工作,但這樣做感覺非常骯髒。

我錯過了什麼,可以讓我在使用es6語法時調用控制器方法,而無需將其指定給$scope

+0

如果您打算使用1.5+,我建議您使用組件,它允許您在組件定義中爲視圖聲明控制器,並且可以使用'$ ctrl'調用它的方法。 – Baruch

回答

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

使用你可以撥打<my-component></my-component>

另一種方法是尼古拉斯塔回答,但如果您使用1.5+只是使用組件,那麼我的意見

1

如果你想使用類作爲控制器(或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-控制器。有關組件的示例,請參閱Baruch的答案。