Reputation: 20545
i have the following userModule
:
(function () {
var userModule = angular.module('user', [
'Auth'
]);
userModule.controller('UserController', ['$http', '$scope', function (UserFactory) {
var uc = this;
uc.user ={}; //set when login
uc.login = login;
function login(username, password)
{
UserFactory.login(username,password).then(function success(reponse){
uc.user = reponse.data
})
}
}]);
userModule.factory('UserFactory', function UserFactory ($http)
{
'use strict';
return{
login: login
};
function login(username, password)
{
return $http.post(API_URL + '/login',
{
username: username,
password: password
});
}
});
})();
Now when i call the login function i get an error telling me that UserFactory is undefined
Can anyone tell me what ive done wrong?
MY Form
<form class="panel-body wrapper-lg" ng-controller="UserController as userCtrl"
ng-submit="userCtrl.login(userCtrl.user.username, userCtrl.user.password)" >
<div class="form-group">
<label class="control-label">Brugernavn</label>
<input type="email" class="form-control input-lg" id="txt_username" name="username"
placeholder="Brugernavn" ng-model="userCtrl.user.username">
</div>
<div class="form-group">
<label class="control-label">Kodeord</label>
<input type="password" name="password" placeholder="Kodeord" class="form-control input-lg"
ng-required="" ng-model="userCtrl.user.password">
</div>
<input type="submit" class="btn btn-lb-primary" value="Log på">
</form>
Upvotes: 0
Views: 502
Reputation: 6176
When defining the controller using an array as the second argument, you're really just telling the angular dependency injection engine what to inject in the function/closure that comes as the last argument. Therefore, you'll have to tell it explicitly to inject UserFactory. In your case, the UserFactory in your controller closure would be an instance of the $http
service.
userModule.controller('UserController', ['$http', '$scope', 'UserFactory', function ($http, $scope, UserFactory) {
var uc = this;
uc.user ={}; //set when login
uc.login = login;
function login(username, password)
{
UserFactory.login(username,password).then(function success(reponse){
uc.user = reponse.data
})
}
}]);
Although I'm not sure it makes any difference, I like to declare my modules, services, etc. in the a chronological order, i.e. create your userModule
first, then make your UserFactory
, and lastly your controller.
As an idea for optimization, try and use the same syntax for your factory as your controller:
userModule.factory('UserFactory', ['$http', function UserFactory ($http)
{
//....
}]);
The reason why the array syntax is used is that when you minify your js, your local variables would have some name that isn't resolvable to a service because angulars dependency injector cannot read the variable name, ultimately looking something like:
userModule.factory('UserFactory', ['$http', function UserFactory (t)
{
//....
}]);
Upvotes: 4