I'm trying to make a web app in Java that connects to a database and shows a table with users.
I have problem with this piece of code in HTML but I believe that this is only the result of earlier coding.
So the code in curly brackets ( {{user.name}} and other) gets underlined and says "Unresolved variable"
I have no idea where is the problem so I'm pasting my angular methods and Java code where I made a list with users that should be displayed in localhost.
This is the code from github that I tried to rewrite but instead of hotels I'm displaying Users.
https://github.com/dangeabunea/RomanianCoderExamples/blob/master/BookingDemo/src/main/resources/templates/index.html
HTML code:
<!-- Display users in a table -->
<table class="table">
<thead>
<tr>
<th>Name</th>
<th>Surname</th>
<th>Login</th>
<th>Is Deleted?</th>
<th style="width: 90px"></th>
</tr>
</thead>
<tbody>
<tr ng-repeat="user in vm.users">
<td>{{user.name}}</td>
<td>{{user.surname}}</td>
<td>{{user.login}}</td>
<td>{{user.isDeleted}}</td>
<td>
<button class="btn btn-danger" ng-click="vm.deleteUser(user.id)">Delete</button>
</td>
</tr>
</tbody>
</table>
JavaScript (angular):
angular
.module('app')
.controller('UserController', UserController);
UserController.$inject = ['$http'];
function UsersController($http) {
var vm = this;
vm.users = [];
vm.getAll = getAll;
vm.deleteUser = deleteUser;
init();
function init(){
getAll();
}
function getAll(){
var url = "/users/all";
var usersPromise = $http.get(url);
usersPromise.then(function(response){
vm.users = response.data;
});
}
function deleteUser(id){
var url = "/users/delete/" + id;
$http.post(url).then(function(response){
vm.users = response.data;
});
}
}
Java:
#Component
public class DatabaseSeeder implements CommandLineRunner {
private UserRepository userRepository;
#Autowired
public DatabaseSeeder(UserRepository userRepository){
this.userRepository = userRepository;
}
#Override
public void run(String... strings) throws Exception {
List <Users> users = new ArrayList<>();
users.add(new Users("John", "Kowalski", "john332", false));
users.add(new Users( "Debby", "Ryan", "debbs84", false));
users.add(new Users( "Michael", "Smith", "grizzly98", false));
userRepository.saveAll(users);
Related
The following code makes up parts of an ASP.NET MVC application that I am currently working on. The index creates a table that the user can add rows by inputting the values for Tag, Server, and Frequency into a popup modal (activated by hitting the "Add" button, modal HTML code not shown). The table's initial values are currently generated by a migration from a linked SQL Database Table (created by using entity-framework).
I am trying to modify this code so that any rows added by the "Add" button will be automatically added to the linked Database Table (preferably by using entity framework). Any help would be appreciated.
Controller
namespace ExampleWebAppilcationTest.Controllers
{
public class HomeController : Controller
{
ExampleDB _db = new ExampleDB();
public ActionResult Index()
{
var model = _db.TData.ToList();
return View(model);
}
protected override void Dispose(bool disposing)
{
if (_db != null)
{
_db.Dispose();
}
base.Dispose(disposing);
}
}
}
Classes
namespace ExampleWebAppilcationTest
{
public class ExampleDB : DbContext
{
public DbSet<TableData> TData { get; set; }
}
}
namespace ExampleWebAppilcationTest
{
public class TableData
{
[Key]
public String Tag { get; set; }
public String Server { get; set; }
public double Frequency { get; set; }
}
}
Index
#model IEnumerable<ExampleWebAppilcationTest.TableData>
#{
ViewBag.Title = "Home Page";
}
#{
ViewBag.Title = "Index";
}
<h2>Table Data</h2>
<table class="table table-bordered" id="mainTable">
<thead>
<tr>
<th></th>
<th class="thTag" scope="col">
#Html.DisplayNameFor(model => model.Tag)
</th>
<th class="thServer" scope="col">
#Html.DisplayNameFor(model => model.Server)
</th>
<th class="thFreq" scope="col">
#Html.DisplayNameFor(model => model.Frequency)
</th>
</tr>
</thead>
<tbody>
<tr>
<td colspan="5">
#foreach (var item in Model)
{
<tr>
<td><input type="checkbox"/></td>
<td>
#Html.DisplayFor(modelItem => item.Tag)
</td>
<td>
#Html.DisplayFor(modelItem => item.Server)
</td>
<td>
#Html.DisplayFor(modelItem => item.Frequency)
</td>
</tr>
</tbody>
</table>
<button type="button" id="addBtn" class="btn btn-success">Add</button>
<!-- The Modals -->
<script>
var table = document.getElementById('mainTable');
// Get the modal
var addmodal = document.getElementById('addModal');
// When the user clicks the button, open the modal
btn.onclick = function () {
addmodal.style.display = "block";
}
var sbtn = document.getElementById("subBtn");
sbtn.onclick = function () {
var table = document.getElementById("mainTable");
var tag = document.getElementById("tag").value;
var server = document.getElementById("server").value;
var frequency = document.getElementById("frequency").value;
var objInputCheckBox = document.createElement("input");
objInputCheckBox.type = "checkbox";
var row = table.insertRow(-1);
var cell1 = row.insertCell(0);
var cell2 = row.insertCell(1);
var cell3 = row.insertCell(2);
var cell4 = row.insertCell(3);
cell1.appendChild(objInputCheckBox);
cell2.innerHTML = tag;
cell3.innerHTML = server;
cell4.innerHTML = frequency;
addmodal.style.display = "none";
}
Although you should have a Layered Architecture for your project with separare Business and DataAccess layers and controller should only be the gateway for incoming requests https://learn.microsoft.com/en-us/dotnet/standard/microservices-architecture/microservice-ddd-cqrs-patterns/infrastructure-persistence-layer-design )
This is what you can do with your current adjustment:
Controller:
namespace ExampleWebAppilcationTest.Controllers
{
public class HomeController : Controller
{
[HttpGet]
public ActionResult Index()
{
using (var dbContext = new ExampleDB())
{
var model = dbContext.TData.ToList();
return View(model);
}
}
[HttpPost]
public ActionResult Index(TableData data)
{
using (var dbContext = new ExampleDB())
{
dbContext.TData.Add(data);
dbContext.SaveChanges();
}
return RedirectToAction("Index");
}
}
}
Data Access
namespace ExampleWebAppilcationTest
{
public class ExampleDB : DbContext
{
public ExampleDB() : base(nameOrConnectionString: "Your Database Connection String") { }
public DbSet<TableData> TData { get; set; }
}
}
namespace ExampleWebAppilcationTest
{
public class TableData
{
[Key]
public String Tag { get; set; }
public String Server { get; set; }
public double Frequency { get; set; }
}
}
View
sbtn.onclick = function () {
var table = document.getElementById("mainTable");
var tag = document.getElementById("tag").value;
var server = document.getElementById("server").value;
var frequency = document.getElementById("frequency").value;
//Here fetch all data in a class
var data = { Tag: tag, Server: server, Frequency: frequency };
//make ajax call to add data
$.ajax({
type: "POST",
url: '#Url.Action("Index", "Home")', //your action
data: data,
dataType: 'json',
success: function (result) {
//to close the popup
},
error: function (result) {
//to show error message
}
});
}
You need to add an Add method of some sort to your controller, decorated with the POST attribute. In your modal, there needs to be a form pointing to the controller's add method url. The form should contain input fields for all of your table properties. That form should be then posted via a submit button to the add method on your controller. The add method needs to take the properties of the form submitted, create a new object, then insert the new object in to the database.
Here's my Spring controller (resource class) method:
#Controller
#RequestMapping("/rest/cart")
public class CartResources {
#Autowired
CartService cartService;
#RequestMapping("/{cartId}")
public #ResponseBody
Cart getCartById (#PathVariable(value = "cartId") int cartId)
{
Cart cart = cartService.getCartById(cartId);
CartItem item = cart.getCartItems().get(0);
Product product = item.getProduct();
System.out.println(product.getProductName());
return cart;
}
}
Here's my angular js class:
var cartApp = angular.module ("cartApp", []);
cartApp.controller("cartCtrl", function ($scope, $http){
$scope.refreshCart = function (cartId) {
$http.get('/eGrocery/rest/cart/'+$scope.cartId).success(function (data) {
$scope.cart=data;
//CODE BELOW IS FOR TESTING PURPOSES
var product = $scope.cart.cartItems[0].product;
var item = $scope.cart.cartItems[0];
if(item == null)
alert("item is null");
else
alert("total price is" + item.totalPrice);
if(product == null)
alert("product is null");
else
alert("product name is" + product.productName);
});
};
$scope.initCartId = function (cartId) {
$scope.cartId = cartId;
$scope.refreshCart(cartId);
};
Here's the HTML file:
<section class="container" ng-app="cartApp">
<div ng-controller = "cartCtrl" ng-init="initCartId('${cartId}')">
<table class="table table-hover">
<tr>
<th>Product</th>
<th>Unit Price</th>
<th>Quantity</th>
<th>Price</th>
</tr>
<tr ng-repeat = "item in cart.cartItems">
<td>{{item.product.productName}}</td>
<td>{{item.product.productPrice}}</td>
<td>{{item.quantity}}</td>
<td>{{item.totalPrice}}</td>
</tr>
</table>
</div>
Brief explanation of the code:
The Spring controller is supposed to pass a Cart object to AngularJS class. The cart object contains cartItem object, which contains a product object.
The problem:
In the AngularJS file, when I try to retrieve any attribute of the Product object, I get null. In fact, the entire product object is null. However, the cartItem object is not null. For instance, I can retrieve the value of cartItem.totalPrice.
The strange thing here is that in the Spring controller class, I explicitly printed out the values of the Product object and they were not null. So, I don't know why AngularJS gets a null Product. Please help.
New to Angular, I am trying to save a form and update the view after calling a PUT or POST call to the backend. Once I receive an OK status from the backend, I am updating my models with the latest response. But only the model in the directive "ng-click" gets updated but others do not. Here is my code:
///HTML
<table class="footable table table-stripped toggle-arrow-tiny" data-page-size="8">
<thead>
<tr>
<th data-toggle="all">Release Title</th>
<th data-hide="all">Release Genre</th>
<th data-hide="all">UID</th>
<th data-hide="all">Classical</th>
<th data-hide="all">Tracks</th>
</tr>
</thead>
<tbody>
<tr ng-repeat="album in vm.albums" footable>
// This one (album.data.title) gets updated but the other ones do not
<td ng-click="vm.editAlbum(album, $index)">{{album.data.title}}</small></td>
<td>{{album.data.genre}}</td>
<td>{{album.data.uid}}</td>
<td ng-if!="album.data.classical">No</td>
<td ng-if="album.data.classical">Yes</td>
<td>
<li ng-repeat="track in album.data.tracks">
<a ng-click="vm.selectTrack(album, track)">{{track.title}}</a>
</li>
</td>
</tr>
</tbody>
<tfoot>
<tr>
<td colspan="5">
<ul class="pagination pull-right"></ul>
</td>
</tr>
</tfoot>
</table>
Here is my controller:
// controller.js (Just pasting the saveRelease method that does the on-click event handling in HTML:
(function (){
angular.module('app.uploadedReleases').controller('UploadedReleasesController', UploadedReleasesController);
UploadedReleasesController.$inject = ['$http', '$log', '$scope', '$state', '$rootScope', 'APP_CONFIG'];
function UploadedReleasesController ($http, $log, $scope, $state, $rootScope, APP_CONFIG){
var vm = this;
vm.albums = []; // list of all albums
vm.albumPriority = [0, 4, 6, 8, 10];
vm.getAlbumTracks = getAlbumTracks;
vm.editAlbum = editAlbum;
vm.selectTrack = selectTrack;
vm.selected = {};
vm.saveRelease = saveRelease;
vm.testingAlbumSelected = false;
return init();
function init(){
$http.get('http://localhost:8080/api/releases').then(function(responseData){
//check the status from the response data.
vm.responseStatus = responseData.status;
if(vm.responseStatus !== 200){
//error message
}
// else, Parse the json data here and display it in the UI
for(var album in responseData.data){
vm.albums.push({slug: album, data: responseData.data[album]});
}
})
}
function getAlbumTracks(slug, index){
$http.get('http://localhost:8080/api/releases/' + slug).success(function(trackResponse){
//parse each album and get the track list
vm.showingAlbumIndex = index;
vm.albums.tracks = [];
vm.selected = {};
vm.selected.album = vm.albums[index];
vm.testingAlbumSelected = true;
for(var i = 0; i<trackResponse.tracks.length; i++) {
vm.albums.tracks.push(trackResponse.tracks[i]);
}
$log.debug(vm.albums.tracks);
vm.formAlbum = new Album(vm.selected.album.data.upc,
vm.selected.album.data.title,
vm.selected.album.data.label,
vm.selected.album.data.genre,
vm.selected.album.data.releaseType,
vm.selected.album.data.holdDate,
vm.selected.album.data.priority,
vm.selected.album.data.memo);
})
}
function selectTrack(album, track){
vm.selected.album = album;
vm.selected.track = track;
vm.testingAlbumSelected = false;
}
function editAlbum(album, index){
getAlbumTracks(album.slug, index);
vm.selected = album;
}
function saveRelease(){
// Call the PUT request to update the release metadata and refresh the page
// so that the Album list gets updated with the latest changes
var url = 'http://localhost:8080/api/releases/' + vm.selected.album.slug;
$http.put(url, vm.formAlbum).then(function(saveAlbumResponse){
if(saveAlbumResponse.status === 202){
//successfully saved response on backend
// Update the current models to show the newer data
vm.album.data = vm.formAlbum;
console.log("album array vm.albums = "+vm.albums);
}
})
}
})();
Any idea why ?
try remove "var vm=this" line. And rename vm.xxxx to $scope.xxxx in your controller.
in the view: remove the "vm."
I'm really new to Angular and i'm trying to create a list of user transactions that presents the time of the action and the user's name. In my audit API I have an action ID and the User FK which associates with my User API and i'm displaying it as follows:
HTML
<table>
<thead>
<tr>
<th>
Date/Time
</th>
<th>
User
</th>
</tr>
</thead>
<tbody>
<tr ng-repeat="audit in audit.data>
<td>{{audit.audit_date_time}}</td>
<td>**{{audit.audit_user_fk}}**</td> **<--I need the name not the ID here**
</tr>
</tbody>
</table>
My Apis are as follows:
AUDIT
[
{
"audit_id": "1",
"audit_date_time": "2016-01-28 12:46:20",
"audit_user_fk": "97"
}
]
USER
[
{
"user_id": "97",
"user_full_name": "Mr.User",
}
]
Controller, which is working fine GETting the data from each API:
app.controller('auditControl', ['$scope','auditService', 'userService', function ($scope, auditService, userService) {
var auditLogs = auditService.query(function () {
$scope.audit.data = auditLogs;
});
var user = userService.query(function () {
$scope.auditUser = user;
});
}]);
So my main issue i'm having is getting the user name in the table instead of the foreign key value. I've stripped out a lot of this just so we can focus on the main problem. Getting the user name from the user API, based on the FK in the Audit API and repeated based on the items in the Audit API.
Any help greatly appreciated and apologies for the noob question!
Create a custom filter.
app.filter("lookupUser", function() {
function lookup (idNum, userList) {
var userName = "UNKNOWN";
angular.forEach(userList, function(user) {
if ( user.user_id == idNum ) {
userName = user.user_full_name;
};
});
return userName;
};
return lookup;
});
Then in your template:
<tr ng-repeat="audit in audit.data>
<td>{{audit.audit_date_time}}</td>
<td>{{audit.audit_user_fk | lookupUser : auditUser }}</td>
</tr>
You could do something like this:
Controller:
app.controller('auditControl', ['$scope','auditService', 'userService', function ($scope, auditService, userService) {
var auditLogs = auditService.query(function () {
$scope.audit.data = auditLogs;
});
var user = userService.query(function () {
$scope.auditUser = user;
});
$scope.getUserName = function (id) {
var result = $scope.users.filter(function( user ) {
return user.user_id == id;
});
if (angular.isDefined(result) && result.length > 0) {
return result[0].user_full_name;
} else {
return "--";
}
}
}]);
HTML
<table>
<thead>
<tr>
<th>
Date/Time
</th>
<th>
User
</th>
</tr>
</thead>
<tbody>
<tr ng-repeat="audit in audit.data">
<td>{{audit.audit_date_time}}</td>
<td>**{{getUserName(audit.audit_user_fk)}}**</td> **<--I need the name not the ID here**
</tr>
</tbody>
</table>
I don't know where the users array are, so I called $scope.users.
I'm writing multiplayer game (Monopoly) in ASP and SignalR.
I've stopped on page which contains a table with list of games.
I have no idea if I'm doing it right:)
So, this is what I've done so far and I need help to move on:
I created GamesList WebForm page with empty table:
<table id="gamesTable">
<thead>
<tr>
<th>#</th>
<th>Number of players</th>
<th>Players</th>
<th>Theme</th>
<th>Join<thead>
</tr>
</thead>
<tbody>
</tbody>
<tfoot>
</tfoot>
</table>
My goal is to populate this table when page loads. Data should be provided by hub:
GamesListHub.cs
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using Microsoft.AspNet.SignalR;
using Newtonsoft.Json;
namespace Obipoly.Hubs
{
public class GamesListHub : Hub
{
public List<GamesItem> games = new List<GamesItem>()
{
new GamesItem(2, "Theme1", "User1"),
new GamesItem(4, "Theme3", "User2")
}; //just for tests
public void gamesListUpdated()
{
string gamesString = JsonConvert.SerializeObject(games);
Clients.All.updateGamesList(gamesString); //pass games list
}
public void addNewGame(int numberOfPlayers, string gameTheme, string hostPlayer) {
games.Add(new GamesItem(numberOfPlayers, gameTheme, hostPlayer));
string gamesString = JsonConvert.SerializeObject(games);
Clients.Others.updateGamesList(gamesString);
}
public void getListOfGames() {
string gamesString = JsonConvert.SerializeObject(games);
Clients.Caller.updateGamesList(gamesString);
}
}
}
This is my javascript code on client side in GamesList.aspx:
<script type="text/javascript">
$(function () {
var gamesListHub = $.connection.gamesListHub;
gamesListHub.client.updateGamesList = function (games) {
console.log(games);
};
$.connection.hub.start().done(function () {
gamesListHub.server.getListOfGames();
});
});
</script>
The problem is I get this: "[{}{}]".
How can I pass this list from signalR to JS method to populate the table?
Thanks.
SOLVED:
var gamesJson = $.parseJSON(games);
for (var i = 0; i < gamesJson.length; i++) {
console.log(gamesJson[i].gameTheme);
}