I want to create a simple login, so I just created a html page with username and password. I created a controller and called a function called login and inside that I called a factory which returns a factory data, and I would create login based on that data.
Controller
myApp.controller('login', ['$scope','$rootScope', '$location', '$window', 'authenticate', '$http', '$cookieStore',function($scope, $rootScope, $location, $window, authenticate, $http, $cookieStore) {
$scope.alert = '';
$scope.login = function(){
authenticate.login($scope.login.username, $scope.login.password).then(function(response){
alert("Inside controller"+JSON.stringify(response));
});
}
}]);
My factory
myApp.factory('authenticate',['$http', '$filter', '$cookieStore', '$rootScope', '$window', '$q',
function($http, $filter, $cookieStore, $rootScope, $window, $q) {
var data = "";
var deferred = $q.defer();
return {
login: function(userName,password){
$http.post('user/serverside/authentication.php',{username: userName, password: password})
.then(function(response){
deferred.resolve(response.data);
alert("FACTORY"+JSON.stringify(response));
});
return deferred.promise;
}
}
}]);
I call the login function inside the controller on login, The issue is when I logged in for
- The first time with one data as expected first alert inside factory executed and then the alert inside the controller is executed.
- But on the second time alert inside controller executed first and the factory alert displaying,
Doubts
- Why the execution sequence change in the second time?
- Is this a right way to use for login, if any better ways please suggest?