I have created an angular application with a simple login form that can be viewed on this JSFiddle.
HTML Code:
<form data-ng-app="jsApDemo" data-ng-controller="loginCtrl">
<label for="username">Username:</label>
<input type="text" id="username" data-ng-model="username" />
<br />
<label for="password">Password:</label>
<input type="password" id="password" data-ng-model="password" />
<br />
<button type="submit" data-ng-click="executeLogIn()">Log in</button>
<br />
<label for="authstatus">Authentication status:</label>
<input type="text" id="authstatus" readonly value="{{ authStatus }}" />
</form>
In my controller loginCtrl
, I have written a function executeLogIn()
which triggers authentication when the user submits the login form.
JavaScript Code:
// Controller and its module
angular.module('jsApDemo', ['Core'])
.controller('loginCtrl', ['$scope', 'Connection', function ($scope, Connection) {
$scope.authStatus = 'unauthenticated';
$scope.executeLogIn = function () {
$scope.authStatus = 'authenticating';
Connection.sessionInitialize({
username: $scope.username,
password: $scope.password
}, function (error, status) {
if (!error) {
/***************************
* ISSUE ARISES HERE
***************************/
$scope.authStatus = status;
}
});
};
}]);
// Service and its module
angular.module('Core', []).service('Connection', function () {
this.sessionInitialize = function (options, callback) {
if (!options || !options.username || !options.password) {
callback('Username and password are mandatory', null);
return;
}
setTimeout(function () {
callback(null, 'authenticated');
}, 1000);
};
});
When trying to update $scope.authStatus
within the callback function of Connection.sessionInitialize
, it does not reflect in the HTML. Although $scope
shows the correct value when logged, the bound textbox #authstatus
remains unchanged.
This appears to be a scoping issue, but I cannot figure out what I am doing wrong. Any suggestions?