I'm testing using es6 with angular 1.6 using browserify and babelify in gulp and I've noticed that when I create a controller using es6 class I can no longer call the controller's methods on the dom using ng-click.
controller:
export default class FocusbtnsController {
constructor($scope) {}
testMethod() {
alert('test method works!!');
}
}
main module:
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>
I've tried removing the export default
from the angular.module
, but with no effect.
when I add the method testMethod
to the $scope
argument $scope.testMethod = testMethod;
it works, but it feels extremely dirty to do it that way.
I'm I missing something that will allow me to call the controller method while using the es6 syntax without having to assign it to the $scope
?
To extend on my comment, a simple Angular 1.5+ component would look like this.
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);
To use you can call <my-component></my-component>
.
An alternative would be what Nicholas Tower answered, but again, in my opinion if you're using 1.5+ just use components.