i am not displaying ajax table in html why? - javascript

I am trying to run an application using AngularJS and Ajax. I also use a Java Controller that returns JSON. Unfortunately, html does not display the table, I cannot understand what is the matter, please help. I am just getting started with Ajax and angularJS. I am trying to output a table in Html, here are my files:
Frames.js
var app = angular.module('frames', []);
app.controller("FramesController", function ($scope, $http) {
$scope.successGetFramesCallback = function (response) {
$scope.frameList = response.data;
$scope.errormessage="";
};
$scope.errorGetFramesCallback = function (error) {
console.log(error);
$scope.errormessage="Unable to get list of frames";
};
$scope.getFrames = function () {
$http.get('/mcga/frames').then($scope.successGetFramesCallback, $scope.errorGetFramesCallback);
};
});
frames.html:
<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml" xmlns:th="http://www.thymeleaf.org"
xmlns:sec="http://www.thymeleaf.org/thymeleaf-extras-springsecurity3">
<head>
<meta charset="utf-8"></meta>
<meta http-equiv="X-UA-Compatible" content="IE=edge"></meta>
<title>Schools in our university</title>
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.8.2/angular.min.js"></script>
<script src="js/frames.js"></script>
</head>
<body ng-app="frames" ng-controller="FramesController">
<h1>Компьютерные корпуса</h1>
<div ng-controller="getFrames" ng-show="frameList.length > 0">
<table id="frameTable">
<thead>
<tr>
<th><h2>Id</h2></th>
<th><h2>Company</h2></th>
<th><h2>Model</h2></th>
<th><h2>Price</h2></th>
<th><h2>Amount</h2></th>
</tr>
</thead>
<tbody>
<tr ng-repeat="frame in frameList" id="{{frame.id}}">
<td>{{frame.id}}</td>
<td>{{frame.company}}</td>
<td>{{frame.model}}</td>
<td>{{frame.price}}</td>
<td>{{frame.amount}}</td>
</tr>
</tbody>
</table>
</div>
</body>
</html>
and my controller is written in java, it gets the list from the Database and returns it in JSON, it works fine. JSON is returned to me. Here is the code:
#RestController
public class MyController {
#Autowired
private Service service;
#GetMapping("mcga/frames")
public ResponseEntity<Object> showAllFrames()
{
List<frame> frameList=service.getAllFrames();
return ResponseEntity.ok(frameList);
}
}
And my ConfigController:
#Configuration
public class ControllerConfig extends WebMvcConfigurerAdapter {
#Override
public void addViewControllers(ViewControllerRegistry registry) {
registry.addViewController("/frames").setViewName("frames");
}
}

You put wrong ng-controller. It must be FramesController: Something like this
<div ng-controller="FramesController" ng-show="frameList.length > 0">
<table id="frameTable">
<thead>
<tr>
<th><h2>Id</h2></th>
<th><h2>Company</h2></th>
<th><h2>Model</h2></th>
<th><h2>Price</h2></th>
<th><h2>Amount</h2></th>
</tr>
</thead>
<tbody>
<tr ng-repeat="frame in frameList" id="{{frame.id}}">
<td>{{frame.id}}</td>
<td>{{frame.company}}</td>
<td>{{frame.model}}</td>
<td>{{frame.price}}</td>
<td>{{frame.amount}}</td>
</tr>
</tbody>
</table>
</div>

Related

SpringBoot how delete selected SQL record (thyme leaf, javascript, java, Doma2)

I want to be able to delete selected SQL record.
If the button next to a record is clicked, a pop-up screen saying "Do you really want to delete it?"
And if yes is clicked,
the record FROM SQL next to the button that was clicked is deleted from the table.
I am really stuck in this, even a little help will help.
<html xmlns:th="http://www.thymeleaf.org">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>selectToDelete</title>
</head>
<body >
<table border="1">
<tr>
<td>name</td>
<td>id</td>
<td>price</td>
</tr>
<tr>
th:each="i : ${#numbers.sequence(session.sessionInfo.input,session.sessionInfo.input2)}">
<td th:text="${session.session2.goodsList[i].G_name}">
<td th:text="${session.session2.goodsList[i].G_id}">
<td th:text="${session.session2.goodsList[i].G_price}">
<td > <button type="submit" name="deleteParam" th:value="${i}" onclick="DeleteButton1(this.value)">selectButton</button></td>
</tr>
</table>
<script th:inline="javascript">
function DeleteButton1(e) {
if (confirm("Do you want to Delete?")) {
window.open('deleteScreen', '_self' );
}else{
console.log(e)
}
}
</script>
</html>
#Controller
#SessionAttributes(value = { "session2" })
public class DeleteScreen {
#RequestMapping(value = "/deleteScreen", method = RequestMethod.GET)
public String skensaku(Model model, #ModelAttribute("sessionInfo") CondTrainingForm condForm) {
return "selectToDelete";
}
}
REPOSITORY↓
package com.example.repository;
import java.util.List;
import org.seasar.doma.Dao;
import org.seasar.doma.Select;
import org.seasar.doma.boot.ConfigAutowireable;
import com.example.domain.CondTrainingEntity;
import com.example.model.CondTrainingForm;
#ConfigAutowireable
#Dao
public interface DbConnectRepository {
#Select
List<CondTrainingEntity> selectDynamic(CondTrainingForm form);
service↓
#Service
#Transactional
public class DbConnectService {
#Autowired
private DbConnectRepository dbConnectRepository;
public List<CondTrainingEntity> selectUser(CondTrainingForm cond) {
return dbConnectRepository.selectDynamic(cond);
}
SQL file↓
SELECT
G_name, G_id,
G_price
FROM
GOODS
WHERE
G_name LIKE /* #infix(form.G_name) */'G_name'
AND
G_id LIKE /* #infix(form.G_id) */'G_id'
AND
G_price LIKE /* #infix(form.G_price) */'G_price'

Call Partial View on button click

I have 2 drop down lists in a Partial View and want to display 1st drop down on 1st Search click and 2nd drop down on 2nd Search click in View. The Index contains list of 2 Students Name and each student has Search button.Please guide me how to write code to display drop down based on button click condition. Any help and guidance is highly appreciated.
My Index View:
#model IEnumerable<StudentProject.StudentDetail>
<table class="table">
<tr>
<th>
#Html.DisplayNameFor(model => model.StudentName)
</th>
</tr>
#foreach (var item in Model) {
<tr>
<td>
#Html.DisplayFor(modelItem => item.StudentName)
</td>
<td>
<input type="button" class="btn btn-info" id="btnSearch" value="Search" />
#Html.ActionLink("Details", "Details", new { id=item.StudentId })
</td>
</tr>
}
</table>
<div id="searchResults">
</div>
<script src="~/Scripts/jquery-1.10.2.min.js"></script>
<script type="text/javascript">
var url = '#Url.Action("DisplaySearchResults", "Student")';
$('#btnSearch').click(function () {
debugger;
$('#searchResults').load(url);
})
</script>
My Partial View _StudentLocation:
<!Doctype html>
<html>
<head>
Locations Details
</head>
<body>
<select class="dropdown">
<option>Auckland</option>
<option>Wellington</option>
</select>
<select class="dropdown">
<option>Hamilton</option>
<option>Christchurch</option>
</select>
</body>
</html>
My Controller:
using System.Linq;
using System.Net;
using System.Web.Mvc;
namespace StudentProject.Controllers
{
public class StudentController : Controller
{
private StudentEntities db = new StudentEntities();
// GET: Student
public ActionResult Index()
{
return View(db.StudentDetails.ToList());
}
// GET: Student/Details/5
public ActionResult Details(int? id)
{
if (id == null)
{
return new HttpStatusCodeResult(HttpStatusCode.BadRequest);
}
StudentDetail studentDetail = db.StudentDetails.Find(id);
if (studentDetail == null)
{
return HttpNotFound();
}
return View(studentDetail);
}
public ActionResult DisplaySearchResults()
{
return PartialView("_StudentLocation");
}
}
}

AngularJS - How to get processed HTML output from $compile?

I have the following function which is fetching custom HTML template and passing some values into the scope to generate 'report table'. Because the template is not visible to the user but processed output is directly sent to another function I used $compile function.
It seems that values passed into the $scope are processed correctly but i am not able to get pure HTML result.
I tried to do it by this way:
var templateUrl = $sce.getTrustedResourceUrl('report.html');
$templateRequest(templateUrl).then(function(template) {
$scope.rows = reportData;
var compTest = $compile(template)($scope);
console.log(compTest); //IT RETURNS A LOT OF VALUES BUT NOT HTML OUPUT OF THE PROCESSED TEMPLATE
}, function() {
// An error has occurred
});
Many thanks for any advice.
Results is following:
HTML content:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Report</title>
</head>
<body>
<table>
<thead>
<td>
</td>
<td>
Breakfast
</td>
<td>
Lunch
</td>
<td>
Dinner
</td>
<td>
Snack
</td>
</thead>
<tbody>
<tr ng-repeat="row in rows">
<td>TEST</td>
<td>40</td>
<td>20</td>
<td>30</td>
<td>10</td>
</tr>
</tbody>
</table>
</body>
</html>
$compile will return a function which will then be executed by scope which in turn will returns a jQlite wrapped DOM object. So you can use outerHTML to get the Template string
or
You can use $interpolate as shown below
Demo
angular.module('myApp', []);
angular
.module('myApp')
.controller('MyController', MyController);
function MyController($scope, $compile, $interpolate) {
var template = '<a ng-click="handler()">click handler</a>';
this.tmpl = $compile(template)($scope)[0].outerHTML;
this.tmplInt = $interpolate(template)($scope);
}
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.6.1/angular.min.js"></script>
<div ng-app="myApp">
<div ng-controller="MyController as MC">
<p><b>using $compile along with outerHTML </b>{{MC.tmpl}}</p>
<p><b>using $interpolate </b>{{MC.tmplInt}}</p>
</div>
</div>

How to select column index from table and set values dynamically using angular.js

I have a doubt regarding how to find row/column index from a table using angular.js .I am explaining one example below.
suppose i have a table with some data which is given below.
sl no name roll-no1 roll-no2 roll-no3 action
1 jack 3 5 7 Change
2 Rahul 4 7 9 change
and the code of this table given below.
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml" ng-app="table">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>Title</title>
<script src="angularjs.js" type="text/javascript"></script>
<script src="app.js" type="text/javascript"></script>
</head>
<body>
<div ng-controller="appController">
<table>
<thead>
<tr>
<th>Sl. No</th>
<th> Name</th>
<th>roll-no1</th>
<th>roll-no2</th>
<th>roll-no3 </th>
<th>Action</th>
</tr>
</thead>
<tbody id="detailsstockid">
<tr ng-repeat="role in userHomeRoleValue">
<td class="role">{{$index+1}}</td>
<td class="role">{{role.user_name}}</td>
<td class="role">{{role.roll1}}</td>
<td class="role">{{role.roll2}}</td>
<td class="role">{{role.roll3}}</td>
<td><button type="button" id="btn" ng-click="changeRow($index)">Change</button></td>
</tr>
</tbody>
</table>
</div>
</body>
</html>
In controller file i have the below line of code.
var app=angular.module('table',[]);
app.controller('appController',function($scope,$http){
$scope.userHomeRoleValue=[
{'user_name':"jack",'roll1':3,'roll2':5,'roll3':7},
{'user_name':"rahul",'roll1':4,'roll2':7,'roll3':9}
]
console.log('user',$scope.userHomeRoleValue);
$scope.changeRow = function(index) {
var rowData = $scope.userHomeRoleValue[index];
// Do whatever you want to change here because the rowData is the row the user clicked the change button on!
}
});
app.directive("test", function() {
return {
scope: false,
link: function(scope, elem, attrs) {
elem.bind('click', function() {
angular.forEach(elem.siblings(), function(value, key) {
if (value.hasClass('role')) {
angular.element(value).text(elem.text());
}
});
});
}
}
});
These table values will display using ng-repeat and values will assign dynamically in controller file.In action column lets say change is the button name.Here i need when user will click on change button of first row,the index of value under roll-no1 will be fetch and that value will update with roll-no2 and roll-no3 values of the same row.Lets assume all table headers are also set dynamically.Please help me.
set ng-click="changeRow($index)" on change buttons.
In your controller add the code below:
$scope.changeRow = function(index) {
var rowData = $scope.userHomeRoleValue[index];
// Do whatever you want to change here because the rowData is the row the user clicked the change button on!
}
UPDATE
For the change you wanted in the comments, make a directive and set the directive to all "rol-no" elements and add a class for tracking them.
<td class="role">{{role.roll1}}</td>
<td class="role">{{role.roll2}}</td>
<td class="role">{{role.roll3}}</td>
app.directive("test", function() {
return {
scope: false,
link: function(scope, elem, attrs) {
elem.bind('click', function() {
angular.forEach(elem.siblings(), function(value, key) {
if (angular.element(value).hasClass('role')) {
angular.element(value).text(elem.text());
}
});
});
}
}
});

Getting and passing MVC Model data to AngularJS controller

I'm pretty new to AngularJS and I'm at a loss here.
Right now my MVC program uses Razor to display all the data in my .mdf database (i.e: #Html.DisplayFor(modelItem => item.LastName) ). However, I want to go mostly Angular. I am trying to use ng-repeat to display all of the Model data, but I am not sure how to pass that Model data to the Angular controller and then use it. I have tried serializing the Model to JSON in my ng-init, but I don't think I'm doing it right (obviously).
Here is my code:
// controller-test.js
var myApp = angular.module('myModule', []);
myApp.controller('myController', function ($scope) {
$scope.init = function (firstname) {
$scope.firstname = firstname;
}
});
<!-- Index.cshtml -->
#model IEnumerable<Test.Models.Employee>
#{
ViewBag.Title = "Index";
}
<div ng-app="myModule">
<div ng-controller="myController" ng-init="init(#Newtonsoft.Json.JsonConvert.SerializeObject(Model))">
<table>
<tr ng-repeat= <!--THIS IS WHERE I'M STUCK -->
</table>
</div>
</div>
<script src="~/Scripts/angular.min.js"></script>
<script src="~/Scripts/controller-test.js"></script>
#Scripts.Render("~/Scripts/angular.js")
I'm not sure exactly what I should be repeating on to get the FirstName from the serialized Model. I feel like I have all the pieces, but just unsure how to connect them.
If you have the key firstName on your Json object like:
{
"employees":[
{"firstName":"John", "lastName":"Doe"},
{"firstName":"Anna", "lastName":"Smith"},
{"firstName":"Peter","lastName":"Jones"}
]
}
You can do it in the following way.
On your controller:
myApp.controller('myController', function ($scope) {
$scope.init = function (employees) {
$scope.employees = employees;
}
});
On your view:
<table>
<tr ng-repeat= "employee in employees">
<td>{{ employee.firstName }}<td>
</tr>
</table>
Thank you to darkstalker_010!
What I was confused was with how my Angular controller file interacted with the view. All I had to do was simply treat my angular {{ }} data in my .cshtml file as if I were trying to access the Model data normally (i.e. model.AttributeName)
So here is the updated, working code:
// controller-test.js
var myApp = angular.module('myModule', []);
myApp.controller('myController', function ($scope) {
$scope.init = function (employees) {
$scope.employees= employees;
}
});
<!-- Index.cshtml -->
#model IEnumerable<Test.Models.Employee>
#{
ViewBag.Title = "Index";
}
<div ng-app="myModule">
<div ng-controller="myController" data-ng-init="init(#Newtonsoft.Json.JsonConvert.SerializeObject(Model))">
<table>
<tr>
<th>First Name</th>
<th>Last Name</th>
<th>Title</th>
<th>Department</th>
<th>Email</th>
</tr>
<tr ng-repeat="e in employees">
<td>{{e.FirstName}}</td>
<td>{{e.LastName}}</td>
<td>{{e.Title}}</td>
<td>{{e.Department.DepartmentName}}</td>
<td>{{e.Email}}</td>
</tr>
</table>
</div>
</div>
<script src="~/Scripts/angular.min.js"></script>
<script src="~/Scripts/controller-test.js"></script>
#Scripts.Render("~/Scripts/angular.js")
Here is what it looks like sans formatting:

Categories

Resources