UI Bootstrap (AngularJS) modal is not working - java

I have this practice project that I am working on, but I cant get my UI Boostratp modal working. Using example from the site https://github.com/angular-ui/bootstrap/tree/master/src/modal I have been trying to implement this feature but without success.
I believe that this is because of that I do not have the knowledge to integrate demo code to my MVC style project (I have separate app.js, controller, and service files), and this one file example is rather confusing to me.
My folder/file structure:
Now, I have tried various things, including making a separate controller, and separate view for modal content (that's why I have bookDetailes.html and bookDetailesConreoller.js files but they are currently out of order - not connected in app.js's stat provider and their code is under comment). This is where I am:
A have a list of basic book details retrieved from data base and printed out in book.html view via data-ng-repeat. In every repeat I have an Action button that is supposed to open modal for editing or deleting that entry.
Here is my book.html file where I have nested the demo markup code from UI Bootsratp site:
<h4 class="text-center"><strong>Book Collection</strong></h4>
<br>
<table class="table table-hover">
<thead>
<tr>
<th>ID</th>
<th>Image</th>
<th>Title</th>
<th>Author</th>
<th>Year</th>
<th>Publisher</th>
<th>City of Publishing</th>
<th>Genre</th>
<th>Action
<th>
</tr>
</thead>
<tbody data-ng-init="init()">
<tr data-ng-repeat="book in books">
<td>{{book.id}}</td>
<td>{{book.image}}</td>
<td>{{book.title}}</td>
<td>{{book.author}}</td>
<td>{{book.yearOfPublishing}}</td>
<td>{{book.publisher}}</td>
<td>{{book.cityOfPublishing}}</td>
<td>{{book.genre}}</td>
<td><a class="btn btn-default" data-toggle="modal" data-ng-click="open()">Action</a></td>
</tr>
</tbody>
</table>
<div>
<script type="text/ng-template" id="myModalContent.html">
<div class="modal-header">
<h3 class="modal-title">I'm a modal!</h3>
</div>
<div class="modal-body">
<ul>
<li ng-repeat="item in items">
<a ng-click="selected.item = item">{{ item }}</a>
</li>
</ul>
Selected: <b>{{ selected.item }}</b>
</div>
<div class="modal-footer">
<button class="btn btn-primary" ng-click="ok()">OK</button>
<button class="btn btn-warning" ng-click="cancel()">Cancel</button>
</div>
</script>
</div>
As you can see, this last part after table tag is supposed to be modal markup taht is called when Action button is pressed and command "open()" i passed to bookController.js via data-ng-click.
My bookControler.js:
collectionsApp.controller('bookController', function($scope, bookService,
$state) {
var books = [];
$scope.save = function() {
bookService.save($scope.book, onSaveDelete);
}
$scope._delete = function(id) {
for (book in books) {
if (book.id === id) {
bookService._delete(book, onSaveDelete);
}
}
}
$scope.edit = function(id) {
for (book in books) {
if (book.id === id) {
$scope.book;
}
}
}
$scope.init = function() {
bookService.list(onInit);
}
// <-- Beginning of the modal controller code I inserted (and adopted) from the example:
$scope.items = [ 'item1', 'item2', 'item3' ];
$scope.open = function(size) {
modalInstance = $modal.open({
templateUrl : 'myModalContent.html',
controller : ModalInstanceCtrl,
size : size,
resolve : {
items : function() {
return $scope.items;
}
}
});
modalInstance.result.then(function(selectedItem) {
$scope.selected = selectedItem;
}, function() {
$log.info('Modal dismissed at: ' + new Date());
});
};
var ModalInstanceCtrl = function($scope, $modalInstance, items) {
$scope.items = items;
$scope.selected = {
item : $scope.items[0]
};
$scope.ok = function() {
$modalInstance.close($scope.selected.item);
};
$scope.cancel = function() {
$modalInstance.dismiss('cancel');
};
};
// <-- Ending of the modal code I have inserted from the example.
onSaveDelete = function(response) {
if (response.data.status === 'success') {
$scope.init();
} else {
alert("DEBUG ALERT: SAVE/DELETE FAIL");
}
};
onInit = function(response) {
$scope.books = response.data;
books = response.data;
};
});
Now, like this, code is working in the seance that data-ng-repeat is working and I get list of database entries on page load. But when I click on the Action button i get this error message in the console:
But when I add $modal to may code like this:
collectionsApp.controller('bookController', function($scope, bookService,
$state, $modal) {
var books = [];
...
I get this error on page load:
Can someone help me understand and implement modals to my project? Thanks in advance... ;)

Add this,
angular.module('Urapp', ['ui.bootstrap']);

Related

How to set link in onClick method in thymeleaf?

When I do a project with jsp, I try to keep it simple. Now I wanted to do project in Thymeleaf. I wanted to show a confirm dialogue box before deleting. I did it. But while I click ok I get an error. I think I cannot set a link properly inside the onclick method.
Here is my html code:
<tr th:each="student,iterStat : ${studentList}">
<td th:text="${student.id}"></td>
<td th:text="${student.roll}"></td>
<td th:text="${student.firstName}"></td>
<td th:text="${student.lastName}"></td>
<td th:text="${student.age}"></td>
<td>
<!-- <a th:href="#{/deleteStudent/(id=${student.id})}">Delete</a> -->
<a href="#" onclick="confirmRemoveQuestion('#{/deleteStudent/(id=${student.id})}')">
Delete
</a>
</td>
<script>
function confirmRemoveQuestion(link) {
if (show_confirm()) {
window.location = link;
this.hide();
} else {
this.hide();
}
}
function show_confirm() {
return confirm("Are you sure you want to do this?");
}
</script>
</tr>
Here is my Controller:
#RequestMapping(value = "/deleteStudent", method = RequestMethod.GET)
public String deleteStudent(#RequestParam(name="id") int id) {
studentService.deleteStudent(id);
return "redirect:/getStudents";
}
Note: Without dialogue box I can delete an object easily. That code is in comment line.
At last i have fixed it. i have replaced the line
Delete
with
Delete
And i have deleted javascript code. Because it is no longer needed!

Displaying database valuees obtained through a RESTful webservice in a JSP pag

I am implementing a messanger using Jax-Rs. I have a client application which use the implemented API. within the database message_id,message,date, sender fields are stored. I need to display these values within a div of jsp page of the client application.
client.jsp
<form action="ClientServlet" method ="post" onclick="onTechIdChange();"></form>
<div id="uploadSuggest" class="center-block">
<div id="suggestHeading" class="row">
<h4 class="textTitle center-block"> Messages </h4>
</div>
<div class="row">
<div class="col-md-8">
<a id="btn_padding" href="#download" class="btn btn-image pull-left" onclick="onTechIdChange();">Create Profile</a>
<p> </p>
</div>
</div>
</div>
</div>
</section>
<script>
function onTechIdChange() {
var urlPath = "http://localhost:8081/messanger/webapi/messages" ;
$.ajax({
url : urlPath,
dataType : "json",
cache: false,
type : 'GET',
success : function(result) {
var details = result[0];
var name;
for(name in details)
{
dispatchEvent(event)
}
alert(details.sender);
},
error : function(jqXHR, exception) {
alert('An error occurred at the server');
}
});
function display(msg) {
var p = document.createElement('p');
p.innerHTML = msg;
document.body.appendChild(p);
}
}
</script>
Through this code nothing is displayed in the div. But values are printed in the tomcat console which ensures that all the methods within API are working properly. Do you have any idea? Thank you in advance
UPDATE
I Updated the javascript code snippet. But nothing is displayed inside the <p> tag
var urlPath = "http://localhost:8081/messanger/webapi/messages" ;
$.ajax({
url : urlPath,
dataType : "json",
cache: false,
type : 'GET',
success : function(result) {
var details = result[0];
var name;
for(name in details.sender)
{
display(name);
}
alert(details.sender);
},
error : function(jqXHR, exception) {
alert('An error occurred at the server');
}
});
function display(msg) {
var p = document.createElement('p');
p.innerHTML = msg;
document.body.appendChild(p);
}
}
This is the section with the <p>
<form action="ClientServlet" method ="post" onclick="onTechIdChange();"></form>
<div id="uploadSuggest" class="center-block">
<div id="suggestHeading" class="row">
<h4 class="textTitle center-block"> Messages </h4>
</div>
<div class="row">
<div class="col-md-8">
<a id="btn_padding" href="#download" class="btn btn-image pull-left" onclick="onTechIdChange();">Create Profile</a>
<p> </p>
</div>
</div>
</div>
</div>
</section>
If somebody knows a tutorial regarding this can you upload a link?
I think you are not calling the display function that add the values to the DOM.
for(name in details){
display(name)
}
Also I am not sure that your parser is correct
success : function(result) {
var details = result[0]; -- Extract the first value of response
var name;
for(name in details) --- should be an array as well
{
dispatchEvent(event) -- I think here you need to call print function
}
alert(details.sender); -- If details.sender have the details probably the
iteration should be for(name in details.sender)
},
Also I reconsider the use of $.ajax, probably use $.get is better and also, use jsp I dont think is needed use a simple html with a javascript.

JQuery to update a <c:forEach> in Spring MVC

I сreated a jsp page with the table. I would like to refresh table after click the button using Jquery.
But in result i see two views at the same time. How to avoid this problem ?
My Controller
#Controller
#RequestMapping("/")
public class HelloController {
private final Logger log = LoggerFactory.getLogger(getClass());
#Autowired
private UserServiceDao userServiceDao;
#RequestMapping(method = RequestMethod.GET)
public String printWelcome(ModelMap model) {
model.addAttribute("Message","first");
model.addAttribute("list",userServiceDao.findAll());
log.trace("NUMBER:::::::::::::::::::::"+userServiceDao.findAll().size());
return "main";
}
#RequestMapping("/table")
public ModelAndView renderTable(HttpServletRequest request) {
String name = request.getParameter("nameSearch");
log.trace("1: "+name);
List<User> people = userServiceDao.find(name);
log.trace("2: "+people.size());
return new ModelAndView("main", "list", people);
}
}
MY view with the Jquery script
<body>
<div class="sear">
<input class=" int datasearch" type="search" value="an" id="dataSearch">
<input class="int search" type="button" value="Search" id="search">
<input class="int create" type="button" id="err" value="Create user">
</div>
<h1>List of users: </h1>
<div class="table" >
<c:forEach var="item" items="${list}">
<div class="row" >
<div id="tabl" class="cell" style="width:300px;"><c:out value="${item.name}"/>></div>
<div class="cell" style="width:100px;" ><input class="delete" type="button" value="Delete user"></div>
<div class="cell"><input class="edit" type="button" value="Edit user"></div>
</div>
</c:forEach>
</div>
<script type="text/javascript">
$('#err').click(function(){
window.location.href='/registration';
})
$('#search').click(function(){
$(function() {
var myTableContainer = $("#tabl");
var renderTable = function(container) {
var data = $('#dataSearch').val();
var postReqData = {}; // Create an empty object
postReqData['nameSearch'] = data;
$.get("/table",postReqData, function(data) {
container.empty().html(data);
})
};
/* This is called on document ready */
renderTable(myTableContainer);
/* Use the same renderTable function when the refresh button is clicked */
$("#search").click(function() {
renderTable(myTableContainer);
});
})
})
Ok, this might be a bit too long for comments.
Your main problem is that both #RequestMapping(method = RequestMethod.GET) and #RequestMapping("/table") render the same view.
That is: the view containing all your search inputs, <c:forEach> table and javascript.
So when you do the search and when the ajax call returns, you replace contents of div#tabl with all those search inputs, <c:forEach> and javascript.
You end up with two pieces of everything nested in the wrong way.
My advice would be to do one RequestMapping that renders the basic jsp, and the other one that renders only the search results (or even returns json and render it as html in javascript).

Receiving jQuery body changes in Wicket

I got a question here regarding Wicket and jQuery. I got a WebPage which is rendered and shown by Wicket. Within this page I got one "draggable" and one "droppable" component, in which the user should be able to move components. This is realized via jQuery. Additionally I got a "Save" button at the end of the WebPage, which should save the new values (if there are any), which means: the newly dropped items. But if I click on "Save" I don't see the newly dropped objects within Wicket, I still just see the objects which have been in the "droppable" area from the beginning on. Here some Code snippets:
HTML:
<div class="container">
<div id="user">
<h1 class="ui-widget-header">Benutzer</h1>
<div class="ui-widget-content" id="userList">
<input type="text" placeholder="Benutzername" id="userNameSearch" />
<ul class="list-group">
<li class="list-group-item" wicket:id="userList"><span
wicket:id="user" id="user"></span><span style="visibility: hidden;" wicket:id="userId" id="userId"></span></li>
</ul>
</div>
</div>
<div id="project">
<h1 class="ui-widget-header">Benutzer im Projekt</h1>
<div class="ui-widget-content" id="project">
<ul class="list-group">
<li class="placeholder list-group-item"><span>Benutzer
in dieses Feld ziehen.</span></li>
<li class="list-group-item" wicket:id="usersInProjectList"><span
wicket:id="userInProject"></span><span style="visibility: hidden;" wicket:id="userInProjectId"></span></li>
</ul>
</div>
</div>
<button id="save" wicket:id="save">Speichern</button>
</div>
<script>
$(function() {
$("#userList li").draggable({
appendTo : "body",
helper : "clone"
});
$("#project ul")
.droppable(
{
activeClass : "ui-state-default",
hoverClass : "ui-state-hover",
accept : ":not(.ui-sortable-helper)",
drop : function(event, ui) {
$(this).find(".placeholder").remove();
var userName = ui.draggable.find("#user").text();
var userId = ui.draggable.find("#userId").text();
$("<li class=\"list-group-item new-project-member\" wicket:id=\"usersInProjectList\"><span wicket:id=\"userInProject\">"+userName+"</span><span style=\"visibility:hidden;\" wicket:id=\"userInProjectId\">"+userId+"</span></li>")
.appendTo(this);
$(ui.draggable).remove();
}
}).sortable({
items : "li:not(.placeholder)",
sort : function() {
// gets added unintentionally by droppable interacting with sortable
// using connectWithSortable fixes this, but doesn't allow you to customize active/hoverClass options
$(this).removeClass("ui-state-default");
}
});
$('#userNameSearch')
.keyup(
function() {
var valThis = $(this).val().toLowerCase();
if (valThis == "") {
$('#userList li').show();
} else {
$('#userList li')
.each(
function() {
var text = $(this)
.text()
.toLowerCase();
(text.indexOf(valThis) >= 0) ? $(
this).show()
: $(this)
.hide();
});
}
;
});
});
</script>
Java Code (Wicket):
ListView userListView = new ListView("userList", finalUserList) {
protected void populateItem(ListItem item) {
User user = (User) item.getModelObject();
item.add(new Label("user", user.getLastname()+", "+user.getFirstname()));
item.add(new Label("userId", user.getId()));
}
};
ListView usersInProjectListView = new ListView("usersInProjectList", usersInProjectList) {
protected void populateItem(ListItem item) {
User user = (User) item.getModelObject();
item.add(new Label("userInProject", user.getLastname()+", "+user.getFirstname()));
item.add(new Label("userInProjectId", user.getId()));
}
};
usersInProjectListView.setOutputMarkupId(true);
add(new AjaxLink<Void>("save")
{
#Override
public void onClick(AjaxRequestTarget target)
{
System.out.println(target.getPage().get("usersInProjectList"));
//window.close(target);
}
});
add(userListView);
add(usersInProjectListView);
You could somehow get the changes from the client to the server, for example using Ajax. You can fire a callback function that can be added via AbstractAjaxBehaviour (see detail here), or maybe switch to wicket-dnd

Calling a jsp/html page using ajax in play 2.0

Can anyone guide me how can i call a jsp/html page using ajax in play framework?
I want to open a lightbox on click of a button and want to load that with a page containing data from database.
Currently i have just displayed the message using ajax. Below is the method inApplication.java
public static Result index()
{
return ok(index.render("Your new application is ready."));
}
My index.scala.html is:
#(products: List[Products])
#import helper._
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.7.1/jquery.min.js" type="text/javascript"></script>
<h1>#products.size() product(s)</h1>
<table border=1>
<tr>
<td>Product Name</td>
<td>Quantity</td>
<td>Price</td>
</tr>
#for(product <- products) {
<tr>
<td>
#product.productname
</td>
<td>
#product.quantity
</td>
<td>
#product.price
</td>
<td id="items">
<input type="button" value="Add Product" name="#routes.Application.user(product.product_id)" id="but"/>
</td>
</tr>
}
</table>
<div class="result1" style="border: 1px solid black; padding: 5px;">not sent yet...</div>
<script type="text/javascript">
jQuery("#items a").click(
function () {
$.get(jQuery(this).attr("href"), function (data) {
$('.result').html(data);
});
return false;
}
)
</script>
You are on the good way.
Create a new action which will return only the html you need in your div (and not the complete html page).
public static Result detail(Integer productId)
{
Product product = .... (productId);
return ok(productDetail.render(product));
}
// with the route of course
productDetail.scala.html
#(product: Product)
My product #product.product_id is beautiful !
....
You must also add a jquery plugin to display your lightbox (there are a thousand...)
Your JsCode will be something like that:
$("#items a").click(function () {
$("#result").load($(this).attr("href"), function() {
displayPopup(); // code this
});
});
(Or maybe a totally different code if the plugin natively handle ajax...)
In resume, there is a lot of work to do, and many ways to do it.
Just try !

Categories