Currently, I am in the process of creating a simple Angular application to enhance my skills. In this app, a list of users is loaded and displayed on the homepage with checkboxes next to each name. Additionally, the number of active users is shown.
The user list functionality seems to be working fine as I have 11 users listed with corresponding checkboxes. However, the actual user names do not appear. The users.length
variable also appears empty.
Below is my core.js
file:
var userApp = angular.module('userApp', []);
userApp.controller("mainController", mainController);
function mainController($scope, $http) {
$scope.formData = [];
// Retrieve all users upon page load
$http.get('/api/users')
.success(function(data) {
$scope.users = data;
console.log(data);
console.log(data.length);
})
.error(function(data) {
console.log('Error: ' + data);
});
// Add new user via API upon form submission
$scope.createUser = function() {
$http.post('/api/users', $scope.formData)
.success(function(data) {
$scope.formData = {};
$scope.users = data;
console.log(data);
})
.error(function(data) {
console.log('Error: ' + data);
});
};
}
And here's my index.html
code snippet:
<html ng-app="userApp">
<head>
<title>Node/Angular Todo App</title>
<link rel="stylesheet" href="//netdna.bootstrapcdn.com/bootstrap/3.0.0/css/bootstrap.min.css">
<script src="//ajax.googleapis.com/ajax/libs/jquery/2.0.3/jquery.min.js"></script>
<script src="//ajax.googleapis.com/ajax/libs/angularjs/1.0.8/angular.min.js"></script>
<script src="core.js"></script>
</head>
<body ng-controller="mainController">
<div class="container">
<div class="jumbotron text-center">
<h1>Users Count: <span class="label label-info"> {{ users.length }}</span></h1>
</div>
<div id="user-list" class="row">
<div class="col-sm-4 col-sm-offset-4">
<div class="checkbox" ng-repeat="user in users">
<label>
<input type="checkbox">{{ user.first_name }}
</label>
</div>
</div>
</div>
<div id="user-form" class="row">
<div class="col-sm-8 col-sm-offset-2 text-center">
<form>
<div class="form-group">
<input type="text" class="form-control input-lg text-center" placeholder="Enter username" ng-model="formData.text">
</div>
<button type="submit" class="btn btn-primary btn-lg" ng-click="createUser()">Add</button>
</form>
</div>
</div>
</div>
</body>
</html>
Example user record:
{
"id": 1,
"first_name": "Bruce",
"last_name": "Lee",
"email": "<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="e587898080a58088848c89cb868a88">[email protected]</a>",
"password": "blee",
"created_at": "2016-01-08T21:49:18.337Z",
"updated_at": "2016-01-08T21:49:18.337Z"
},
While the data is successfully logged in the console, I'm facing issues with displaying the user information properly.
If anyone can lend a hand, it would be greatly appreciated!
Thank you! 🙏