Reputation: 2005
I'm trying to inject dependencies into functions but it does not seem to be working. Am I doing something wrong or should I do something different instead of trying to inject the dependencies into the function? I'm trying to get the following piece of code working:
angular.module('app').controller('usersController', usersController);
usersController.$inject = ['$http', '$cookies'];
function usersController($http, $cookies) {
var self = this;
self.isLoggedIn = ($cookies.get('token') && $cookies.get('secret'));
register.$inject = ['$http', '$cookies'];
self.register = register;
function register($http, $cookies) {
console.log(self.username);
$http.post('/register', {
username: self.username,
password: self.password,
email: self.email
}).then(function successCallback(response) {
self.isLoggedIn = true;
$cookies.put('token', response.data.token);
$cookies.put('secret', response.data.secret);
}, function errorCallback(response) {
console.log('Something went wrong.');
});
};
};
Upvotes: 0
Views: 80
Reputation: 165070
You don't have to. $http
and $cookies
are already available in that scope
function usersController($http, $cookies) {
// ...
this.register = function() {
$http.post(...)
// and so on
}
}
Upvotes: 1
Reputation: 106528
This looks inappropriate for a couple of reasons; your controller already has those services injected, so it makes little sense to inject them again, and from what I can tell, no state needs to be passed into your function for it to actually work.
This would be cleaner - remove the extraneous $inject
and clean up the function params list.
angular.module('app').controller('usersController', usersController);
usersController.$inject = ['$http', '$cookies'];
function usersController($http, $cookies) {
var self = this;
self.isLoggedIn = ($cookies.get('token') && $cookies.get('secret'));
self.register = register;
function register() {
console.log(self.username);
$http.post('/register', {
username: self.username,
password: self.password,
email: self.email
}).then(function successCallback(response) {
self.isLoggedIn = true;
$cookies.put('token', response.data.token);
$cookies.put('secret', response.data.secret);
}, function errorCallback(response) {
console.log('Something went wrong.');
});
}
}
Upvotes: 1