I have a form with 2 fields: username and password.
When my username model changes, I make a request to an API to perform some checks.
When I make x calls separated by t milliseconds to a $resource
factory, I would like to know if :
- in my controller, the last
$promise
received will correspond to the last input made by the user. - previous promises will be cancelled.
I tried to find out a way to simulate a delay on my API call (because I am working locally and each response is immediate) but I could just find examples for $http
service.
Here is a jsFiddle to expose this case:
http://jsfiddle.net/Jfwh9/1/
HTML
<div ng-app="myApp">
<form ng-controller="loginCtrl">
Username: {{ username }}
<br>Password: {{ password }}
<br>
<input name="username" placeholder="enter your username" type="text"
ng-model="username" ng-change="checkUsername()">
<input name="password" placeholder="enter your password" type="password"
ng-model="password">
</form>
</div>
App
var myApp = angular.module('myApp', ['ngResource']);
/*
* PRE-LOGIN
*
*/
myApp.factory( 'preLogin', ['$resource',
function( $resource, constants ) {
// Check if a username exists
return $resource( '/api/prelogin', {},
{
post: {
method : 'POST'
}
});
}]);
/*
* Login Controller
*
*
*/
myApp.controller('loginCtrl', ['$scope', 'preLogin',
function( $scope, preLogin ) {
$scope.username = '';
$scope.password = '';
// Do some check on the username...
$scope.checkUsername = function() {
console.log('prelogin... ', $scope.username);
preLogin.post({
username: $scope.username
}).$promise.then( function( data ) { // Success
console.log(data);
}, function( error ) { // Error
console.log(error);
});
}
}]);
Thanks!