I'm writing a directive and trying to stick to the John Papa style guide. So I've also decided to jump on the ControllerAs
syntax wagon and I've got a tiny directive like below:
(function() {
angular
.module('htApp')
.directive('newsletterSignup', newsletter_signup);
function newsletter_signup($http) {
var directive = {
templateUrl: '../whatever.tpl.html',
restrict: 'EA',
controller : controller,
controllerAs: 'vm',
bindToController: true
};
return directive;
controller.$inject = ['$http'];
function controller($http) {
var vm = this;
// $http is here ... all is good, but I don't need it
function doSubmit(form) {
// I need $http here, but it is null
debugger;
};
vm.doSubmit = doSubmit;
}
}
})();
This is a newsletter signup service. I'm going to have to do an HTTP request, therefore I'm injecting it into the controller. All is fine - but calling the vm.doSubmit(--formname-here--)
function from the template results in me not being able to find the $http
service.
So my question: how can I access the injected $http
from the doSubmit()
function?
EDIT
I'll include the view code - but no worries - the plumbing works:
<button class="btn btn-yellow" ng-click="vm.doSubmit(newsletterform)" translate>
footer.ok_button_text
</button>
EDIT 2
As it turns out, @Tek was right - the code works. I think the reason I didn't see it was because (I think) the JS runtime in Chrome optimizes the $http
away when it knows it's not going to be called.
This code works fine. I think this is because the runtime aniticipated the usage of $http
in the console.log()
function call. However - if I remove that line I get this ( which was why I had this problem in the first place ):
Notice that I commented out the console.log
- thus the doSubmit()
call never uses $http
. Now - when I call $http
in the console - it's not defined.
Your example works just fine: example.
But as for me John Papa has pretty strange vision of angular style, I prefer this style guide.