I'm brand new to AngularJS. I would like advice as to whether I'm approaching the design of a simple login section of an app built with Angular correctly.
The app consists of two view partials: login.html and user-admin.html. Of what I have so far, the user types their username into the login page. A controller checks if that username is listed in users.json file, if so then login is successful and the user-admin.html partial replaces login.html.
I feel that the controller which checks the typed username against the usernames in users.json could be written better. Is there a more efficient way than using the 'for' statement?
To develop this further I will want to add some way of preventing a logged in user seeing the login page and a non-logged in user seeing the admin page. My initial thought is to use cookies. But would the 'Angular' way be to create a service that perpetuates the logged in status between views? If that is the best way to implement it, what would that service look like?
app.js
angular.module('userApp', ["ngResource"]).
config(['$routeProvider', function($routeProvider) {
$routeProvider.
when('/login', {templateUrl: 'partials/login.html', controller: LoginCtrl}).
when('/loggedin', {templateUrl: 'partials/user-admin.html', controller: UserCtrl}).
otherwise({redirectTo: '/login'});
}],[ '$locationProvider', function($locationProvider) {
$locationProvider.html5Mode = true;
}]).
factory("User", function($resource) {
return $resource("users/:userId.json", {}, {
query: {method: "GET", params: {userId: "users"}, isArray: true}
});
});
controllers.js
function LoginCtrl($scope, $route, $routeParams, $location, User) {
$scope.users = User.query();
$scope.loginUser = function() {
var loggedin = false;
var totalUsers = $scope.users.length;
var usernameTyped = $scope.userUsername;
for( i=0; i < totalUsers; i++ ) {
if( $scope.users[i].name === usernameTyped ) {
loggedin = true;
break;
}
}
if( loggedin === true ) {
alert("login successful");
$location.path("/loggedin");
} else {
alert("username does not exist")
}
}
}
function UserCtrl($scope, $route, $routeParams, $location) {
$scope.logoutUser = function() {
$location.path("/login");
}
}
users.json
[
{
"userId": 1,
"name": "Tommy",
"password": "123456",
"log": {
"registration": "2012.12.14",
"lastLog": "2013.01.15"
}
},
{
"userId": 2,
"name": "Anne",
"password": "123456",
"log": {
"registration": "2012.12.24",
"lastLog": "2012.12.29"
}
},
{
"userId": 3,
"name": "Miles",
"password": "abc",
"log": {
"registration": "2013.02.01",
"lastLog": "2013.02.01"
}
}
]
login.html
<h1>Login</h1>
<section>
<form ng-submit="loginUser();">
<label for"userUsername">Username</label><input type="text" id="userUsername" ng-model="userUsername">
<input type="submit" value="Login">
</form>
</section>