I'm creating a new custom RESTful web service (managed with Spring framework) on a Jhipster app that search on objects Request containing a text that I give in input.
I tested the REST call from html and Angular.js and it works fine. The only one problem is that I don't know how could I parse the result in a html page instead of .json format.
My html code (located in "src/main/webapp/app/layouts/navbar/navbar.html") that call REST is this:
<form class="navbar" method="GET" action="/api/search">
<input style="margin-top: 2.8%; margin-right:2px;" class="btn" type="text" name="content" placeholder="Search requests..." />
<input style="margin-top: 2.8%; margin-right:5px;" class="btn btn-primary" type="submit" text="Search" value="Search">
</form>
My "navbarController.js" is this:
(function () {
'use strict';
angular
.module('businessRequestApp')
.controller('NavbarController', NavbarController);
NavbarController.$inject = ['$state', 'Auth', 'Principal', 'ProfileService', 'LoginService', 'Request'];
function NavbarController($state, Auth, Principal, ProfileService, LoginService, Request) {
var vm = this;
vm.isNavbarCollapsed = true;
vm.isAuthenticated = Principal.isAuthenticated;
ProfileService.getProfileInfo().then(function (response) {
vm.inProduction = response.inProduction;
vm.swaggerEnabled = response.swaggerEnabled;
});
vm.login = login;
vm.logout = logout;
vm.toggleNavbar = toggleNavbar;
vm.collapseNavbar = collapseNavbar;
vm.$state = $state;
vm.requests = [];
loadAll();
function loadAll() {
Request.query(function (result) {
vm.requests = result;
vm.searchQuery = null;
});
}
function login() {
collapseNavbar();
LoginService.open();
}
function logout() {
collapseNavbar();
Auth.logout();
$state.go('home');
}
function toggleNavbar() {
vm.isNavbarCollapsed = !vm.isNavbarCollapsed;
}
function collapseNavbar() {
vm.isNavbarCollapsed = true;
}
}
})();
My java REST ("RequestResource.java") is this:
#GetMapping("/search")
#Timed
public ResponseEntity<List<Request>> searchRequest(#RequestParam String content) {
log.debug("REST request to get Request : {}", content);
List<Request> requestsFounded = findByContentContaining(content);
return ResponseUtil.wrapOrNotFound(Optional.ofNullable(requestsFounded));
}
When I click the button I receive this .json (that is a list of matching Request that I searched for - based on parameter content give in input):
[ {
"id" : 13,
"requestTitle" : "Titolo",
"content" : "Richiesta",
"creationDate" : "2017-06-23",
"authorUsername" : "admin",
"author" : null,
"referencedTable" : {
"id" : 3,
"usersOnIt" : "",
"name" : "Tavolo 1"
}
}, {
"id" : 14,
"requestTitle" : "Voglio vedere Tiziano Ferro",
"content" : "Mi piacerebbe vedere tiziano per fare ...",
"creationDate" : "2017-06-25",
"authorUsername" : "admin",
"author" : null,
"referencedTable" : {
"id" : 4,
"usersOnIt" : "alfa",
"name" : "Tavolo 3"
}
}, {
"id" : 19,
"requestTitle" : "Titolo",
"content" : "Voglio vedere Marco",
"creationDate" : "2017-06-26",
"authorUsername" : "user",
"author" : null,
"referencedTable" : null
} ]
So, my final question is: how could I translate that .json objects list into an html table?
I've been searching a lot on the web but I found nothing, I hope someone will help me.
Thanks in advice for your time,
Manuel.
You can call a function on form submit and get the json in your vm instance inside your function
HTML
<form class="navbar" ng-submit="vm.getJson()">
<input style="margin-top: 2.8%; margin-right:2px;" class="btn" type="text" name="content" ng-model="vm.content" placeholder="Search requests..." />
<input style="margin-top: 2.8%; margin-right:5px;" class="btn btn-primary" type="submit" text="Search" value="Search">
</form>
<tr ng-repeat="value in json"><td>{{value }}</td></tr>
JS:
vm.getJson=function(){
$http.get("YourUrl",vm.content).then(function(response){
vm.json=response.data;
console.log(response);
})
}
Related
I have a AngularJS app where I take in user input and store it in a painting objects and then send it to my spring boot back-end that will store it to the Mongodb server and return an id, however when I try go POST anything to the server i get an empty response back, even though the object gets stored in the server.
AngularJS code:
<!DOCTYPE html>
<html lang="en-US">
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.7.1/angular.min.js"></script>
<body>
<div ng-app="myApp" ng-controller="myCtrl">
<p>Name : <input type="text" ng-model="name"></p>
<h1>Hello {{name}}</h1>
<br>
<br>
<br>
URL : <input type="text" ng-model="painting.url"><br>
Artist : <input type="text" ng-model="painting.artist"><br>
ArtistInfo : <input type="text" ng-model="painting.artistInfo"><br>
Title : <input type="text" ng-model="painting.title"><br>
Dated : <input type="text" ng-model="painting.dated"><br>
Medium : <input type="text" ng-model="painting.medium"><br>
Dimensions : <input type="text" ng-model="painting.dimensions"><br>
Credit : <input type="text" ng-model="painting.credit"><br>
<button ng-click="submit()">Post</button>
<pre>{{painting | json}}</pre>
</div>
<script>
var app = angular.module('myApp', []);
app.controller('myCtrl', ['$scope','$http', function($scope,$http) {
$scope.name = "";
$scope.painting = {
url: '',
artist: '',
artistInfo: '',
title: '',
dated: '',
medium: '',
dimensions: '',
credit: ''
};
$scope.submit = function(){
console.log(JSON.stringify($scope.painting));
$http({
method: 'POST',
headers: {
'Content-Type': 'application/json'
},
url: 'http://localhost:8080/paintings',
data: $scope.painting
}).then(function (response) {
console.log(response);
}, function (response) {
console.log("Error");
console.log((JSON.stringify(response)));
});
//$http.post('http://localhost:8080/paintings', $scope.painting).catch(console.error);
};
}]);
</script>
</body>
</html>
SpringBoot Java POST Method:
#RequestMapping(method = RequestMethod.POST, value = "/paintings")
public String save(#RequestBody Painting painting){
repository.save(painting);
System.out.println("Function called");
return painting.getID();
}
PostMan Response:
Not sure why I'm getting an empty response when I check the console in a browser, even though the server is sending back a response.
I think you need to access the data property of the response,
.then(function (response) {
console.log(response.data);
}
What I ended up doing with the help of #Sajeetharan is edit my backend post request to
#RequestMapping(method = RequestMethod.POST, value = "/paintings")
public ResponseEntity<String> save(#RequestBody Painting painting){
repository.save(painting);
System.out.println("Function called");
JSONObject json = new JSONObject();
json.put("id",painting.getID());
return ResponseEntity.ok(json.toString());
}
I'm new to Angular-js. I'm using JSP for front end and passing values from UI to controller.Now I need to open a new popup list where user can select an option, then pass all parameters to service ..
ng-click="rewardRetry(singleWinner)"
controller --->
$scope.retryRewardDTO = {
"mobile_number" : null,
"draw_id" : 0,
"lottery_ticket_id" : 0,
"prize" : 0,
"reward_method" :null
};
(mobile_number,draw_id,lottery_ticket_id,prize) I can assign like this
$scope.rewardRetry = rewardRetry;
function rewardRetry(rewardRetryDTO) {
$scope.retryRewardDTO.draw_id=rewardRetryDTO.draw_id;
$scope.retryRewardDTO.lottery_ticket_id=rewardRetryDTO.lottery_ticket_id;
$scope.retryRewardDTO.prize=rewardRetryDTO.prize;
$scope.retryRewardDTO.mobile_number=rewardRetryDTO.mobile_number;
//$scope.retryRewardDTO.reward_method=rewardRetryDTO.reward_method;
}
But here retryRewardDTO.reward_method -->user should be select in popup option. (wallet,m_cash,reload,,, ....etc)
calling to service
winnerService.winnerService.rewardRetry(
$scope.retryRewardDTO,
function(data, headers) {
winnerSearch();
}, function() {
});
I'm trying do something like below link.but couldn't get a proper output.please some helps to me...
visit :AngularJS Modal Popup
Finally I found the answer and here implemented new rewardService
$scope.rewardRetry = rewardRetry;
function rewardRetry(rewardRetryDTO) {
$scope.retryRewardDTO.draw_id=rewardRetryDTO.draw_id;
$scope.retryRewardDTO.lottery_ticket_id=rewardRetryDTO.lottery_ticket_id;
$scope.retryRewardDTO.prize=rewardRetryDTO.prize;
$scope.retryRewardDTO.mobile_number=rewardRetryDTO.mobile_number;
//$scope.retryRewardDTO.reward_method=rewardRetryDTO.reward_method;
var modalOptions = {
bodyText : 'Are you sure you want to retry '+$scope.retryRewardDTO.prize+'/= reward for 0'+ $scope.retryRewardDTO.mobile_number+' ? Please select a reward method first and confirm'
};
rewardService.showModal({}, modalOptions).then(
function(result) {
$scope.retryRewardDTO.reward_method = result;
$('#retry-'+rewardRetryDTO.draw_id+'-'+rewardRetryDTO.lottery_ticket_id).hide();
$timeout(function() {
winnerService.winnerService.rewardRetry(
$scope.retryRewardDTO,
function(data, headers) {
winnerSearch();
}, function() {
});
});
});
}
;
My reward_option.jsp file
<%# taglib prefix="sec"
uri="http://www.springframework.org/security/tags"%>
<div class="option">
<div class="pull-right"></div>
<div>Copyright © Lucky889 2016</div>
<input type="hidden" value="<sec:authentication property="principal.userType" />" id="user_type" />
<input type="hidden" value="<sec:authentication property="principal.operator" />" id="user_operator" />
</div>
<script type="text/ng-template" id="rewardModalContent.html">
<div class="modal-header">
<h3>{{modalOptions.headerText}}</h3>
</div>
<div class="modal-body">
<p>{{modalOptions.bodyText}}</p>
<div class="modal-body">
<%-- <p ng-repeat="(key,singleReward) in modalOptions.rewardList">{{key}}----{{singleReward}}</p> --%>
<div class="form-group">
<label class="control-label" for="reward">Reward
Method</label><select name="reward" id="reward"
ng-model="reward_method" class="form-control">
<option ng-repeat="(key,singleReward) in modalOptions.rewardList"
value="{{key}}">{{singleReward}}</option>
</select>
</div>
</div>
<div class="modal-footer">
<button class="btn btn-primary"
data-ng-click="modalOptions.confirm(reward_method)">{{modalOptions.actionButtonText}}</button>
<button type="button" class="btn"
data-ng-click="modalOptions.cancel()">{{modalOptions.closeButtonText}}</button>
</div>
</script>
Here is my rewardService
angular.module("zmessengerRewardApp.service", []).service(
'rewardService',
function(toastr, $uibModal, $log) {
var showHeaderErrorMessage = function(header) {
toastr.clear();
toastr.error(header['lms-message'],
header['lms-root-cause-message']);
};
var showHeaderSuccessMessage = function(header) {
toastr.clear();
toastr.success(header['lms-message'],
header['lms-root-cause-message']);
};
var modalDefaults = {
backdrop : true,
keyboard : true,
modalFade : true,
templateUrl : 'rewardModalContent.html'
};
var modalOptions = {
closeButtonText : 'Cancel',
actionButtonText : 'Confirm',
headerText : 'Confirmation',
bodyText : 'Perform this action?',
rewardList : {reload:'Auto Reload',manual_reload:'Manual Reload',ez_cash:'Ezcash',mcash:'MCash',wallet:'Wallet',bank:'Bank Transfer'}
};
function showModal(customModalDefaults, customModalOptions) {
if (!customModalDefaults)
customModalDefaults = {};
customModalDefaults.backdrop = 'static';
return show(customModalDefaults, customModalOptions);
};
function show(customModalDefaults, customModalOptions) {
// Create temp objects to work with since we're in a singleton
// service
var tempModalDefaults = {};
var tempModalOptions = {};
// Map angular-ui modal custom defaults to modal defaults
// defined in service
angular.extend(tempModalDefaults, modalDefaults,
customModalDefaults);
// Map modal.html $scope custom properties to defaults defined
// in service
angular.extend(tempModalOptions, modalOptions,
customModalOptions);
if (!tempModalDefaults.controller) {
tempModalDefaults.controller = function($scope,
$uibModalInstance) {
$scope.modalOptions = tempModalOptions;
$scope.modalOptions.confirm = function(result) {
$uibModalInstance.close(result);
};
$scope.modalOptions.cancel = function(result) {
$uibModalInstance.dismiss('cancel');
};
}
}
return $uibModal.open(tempModalDefaults).result;
};
return {
showHeaderErrorMessage : showHeaderErrorMessage,
showHeaderSuccessMessage : showHeaderSuccessMessage,
showModal : showModal,
};
});
I'm trying to learn AngularJs and writing some throw away code. I'm trying to create an object Bookmark and push it into an array.
HTML:
<h2>Create a new bookmark </h2>
<form class="form-group" ng-submit="createBookmark(newBookmark)" novalidate>
<!--Title-->
<h4>Bookmark Title</h4>
<input type="text" ng-model="newBookmark.title">
<!--Url-->
<h4>Bookmark Url</h4>
<input type="text" ng-model="newBookmark.url">
<!--Submit-->
<button type="submit" href="#" class="btn btn-primary" id="crForm" ng-click="stopCreating()">Save</button>
</form>
JS:
function resetCreateForm(){
$scope.newBookmark = {
title : '',
url : '',
category : $scope.currentCategory.name
};
}
function createBookmark(bookmark) {
bookmark.id = $scope.bookmarks.length;
bookmark.category = $scope.currentCategory.name;
$scope.bookmarks.push(bookmark);
resetCreateForm();
}
$scope.createBookmark = createBookmark;
$scope.resetCreateForm = resetCreateForm;
Object:
$scope.bookmarks = [
{id: 0, title: "Title1", url: "www.Title1.com", category: "Development"},
{id: 1, title: "Title2", url: "www.Title2.com", category: "Development"}
];
Module and Controller:
var app = angular.module('list',[]);
app.controller('listController', function($scope){
For some reason it does not work, so far I think it's from changes in the Angular version but I could not find a way to make it work.
You have to bind resetCreateForm & createBookmark in $scope of controller so that you can access them from view.
//place this inside your controller
$scope.resetCreateForm = resetCreateForm;
$scope.createBookmark= createBookmark;
Also you don't need to call function on ng-click, on click of button ng-submit will get called. Remove ng-click="stopCreating()"
I am trying to update a program for updating and inserting into mongodb, but I keep getting an error. Let me paste the relevant code here, and I hope to get some help.
PosProductVariant.js
module.exports = {
schema : true,
attributes: {
// unique name identifier
name : { type: 'text', unique : true , required : true },
product : { model : 'PosCustomProduct' },
additionalPrice : { type : 'integer', defaultsTo: 0 },
// assets
display : { model : 'CmsProductVariant' },
// store referrer
store : { model : 'SystemStore' }
}
};
CmsProductVariant.js
module.exports = {
schema : true,
attributes: {
// custom product variant reference
product : { model : 'PosProductVariant' },
// custom title
title : { type : 'string' },
gallery : { type : 'array' , defaultsTo : [] }, // main gallery
}
};
PosProductController.js
module.exports = {
updatePricing : function(req,res,next){
// get pricing parameters
var pricing = req.allParams(),
query = {};
// parameters violation
if(!pricing.additionalPrice)
return res.badRequest();
// compose query
for(var attr in pricing){
if(attr !== 'additionalPrice' && _.isArray(pricing[attr])){
query[attr] = pricing[attr];
}
}
sails.log.verbose('pricing parameter');
sails.log.verbose(pricing);
sails.log.verbose('update query');
sails.log.verbose(query);
PosProductVariant.update(query,{
additionalPrice : pricing.additionalPrice,
display : pricing.display.gallery
})
.then(function(_variant){
if(!_variant) throw 'Cant update Variant';
res.ok();
})
.catch(function(error){
sails.log.error(error);
res.serverError(error);
});
}
};
pricing.html
<form class="grid-fluid grid-parent" name="pricingForm" ng-if="isDefined(product)"
ng-disabled="isProcessing" ng-submit="updatePricing()" novalidate>
<div class="form-group grid-50" ng-repeat="(attr, options) in product.attributes">
<label>{{attr}}</label>
<select multiple ng-model="pricing[attr]" class="form-control" ng-options="option for option in options" required></select>
</div>
<div class="form-group grid-100">
<label>add price</label>
<input type="number" class="form-control" ng-model="pricing.additionalPrice" placeholder="add price" required />
</div>
<div class="form-group grid-100">
<carousel class="bg-dark">
<slide ng-repeat="slide in pricing.display.gallery" active="slide.active" index="$index">
<img ng-src="{{slide.gallery}}" style="margin:auto;">
<div class="carousel-caption">
<a class="button button-error button-labeled"
ng-click="removeItem(pricing.display.gallery,$index)">
<span class="button-label"><i class="icon icon-trash-a"></i></span>
delete image
</a>
</div>
</slide>
</carousel>
<hr/>
<div class="form-group">
<label>tambahan galeri</label>
<file-uploader class="form-control"
image-width="{{galleryConfigs.width}}"
image-height="{{galleryConfigs.height}}"
image-crop-width="{{galleryConfigs.width}}"
image-crop-height="{{galleryConfigs.height}}"
max-size="5000"
allowed-extensions="png,jpeg,jpg"
result-model="addGallery">
</file-uploader>
</div>
</div>
<!-- action -->
<div class="form-group grid-100">
<hr/>
<button type="submit" class="button button-primary button-labeled"
ng-disabled="pricingForm.$invalid || pricingForm.$pristine || isProcessing" >
<span class="button-label"><i class="icon icon-paper-airplane"></i></span>
Update Pricing
</button>
<button class="button button-default button-labeled pull-right" role="action"
ng-click="goBack()" ng-disabled="isProcessing">
<span class="button-label"><i class="icon icon-android-close"></i></span>
Back
</button>
</div>
</form>
And controller pricing.js
var store = {},
id = $stateParams.modelId,
filter = {};
// get current active store
store = authService.getCurrentStore($scope);
if(!store){
// session expired
$scope.$emit(GLOBAL_EVENTS.SYSTEM.STORE.SESSION_TIMEOUT);
return;
}
// init scope
$scope.product = {};
$scope.pricing = {
display: {
gallery: []
}
};
moduleConfigResolver.syncStoreConfig(store.id)
.then(function(STORE_CONFIG){
// get gallery image size configs
$scope.galleryConfigs = {
height : [STORE_CONFIG.POS_PRODUCT_ZOOM_HEIGHT,
STORE_CONFIG.POS_PRODUCT_GALLERY_HEIGHT,
STORE_CONFIG.POS_PRODUCT_THUMBNAIL_HEIGHT],
width : [STORE_CONFIG.POS_PRODUCT_ZOOM_WIDTH,
STORE_CONFIG.POS_PRODUCT_GALLERY_WIDTH,
STORE_CONFIG.POS_PRODUCT_THUMBNAIL_WIDTH]
};
});
// add gallery image
$scope.addGallery = function(imageSrc){
if(!angular.isArray(imageSrc) || imageSrc.length < 3)
return;
$scope.pricing.display.gallery.push({
zoom : imageSrc[0],
gallery : imageSrc[1],
thumbnail : imageSrc[2]
});
};
// if has url params
if(id){
dataProvider.CustomProduct.get({'id':id}).$promise
.then(function(_product_customize){
$scope.product = angular.copy(_product_customize);
})
.catch(function(error){
$log.error(error);
});
It looks to me that the form does not submit data gallery, as the parameters are printed as undefined/null in my posproductcontroller and get an error.
{
"error": "E_VALIDATION",
"status": 400,
"summary": "1 attribute is invalid",
"model": "CmsProductVariant",
"invalidAttributes": {
"hashedPassword": [
{
"display": CmsProductVariant,
"message": "`undefined` should be a string (instead of \"null\", which is a object)"
}
]
}
}
what is my problem with my code? Help me please Sir?
So, I have a select input within a angular repeated item. I want to use a button to assign rooms to a person. As well as maintain if a person has rooms selected, it will show that it is already assign within the selection input.
Here my Firebase Data:
{
"-JLtuRmYiTDLTnZPj" : {
"last_name" : "NameOne",
"person_id" : 1,
"is_in" : false
},
"-JLtuRBlyWhHV28zd" : {
"last_name" : "NameTwo",
"person_id" : 2,
"is_in" : false
},
"-JLtuQxlMn25APuKT" : {
"last_name" : "NameThree",
"person_id" : 3,
"is_in" : false
}
}
Here is my code:
<table>
<tbody>
<tr ng-repeat="(name, person) in people | orderBy: 'doctor_id'" ng-model="person">
<td>{{person.person_id}}</td>
<td>{{person.last_name}}</td>
<td><strong>{{person.is_in}}</strong></td>
<td>Assign Rooms: <select multiple class="form-control" ng-model="person.room_id" ng-options="r.room_id as r.name for (key, r) in rooms"></select></td>
<td><button type="button" href="" class="btn btn-primary" ng-click="assignRooms(name)">Assign Rooms</button></td>
</tr>
</tbody>
</table>
And Finally my JS:
angular.module('app', ['ngRoute', 'firebase']);
$scope.people = $firebase(new Firebase("https://<FB-NAME>.firebaseio.com/dev/0/people"));
$scope.rooms = $firebase(new Firebase("https://<FB-NAME>.firebaseio.com/dev/0/rooms"));
//Assigns Rooms to each doctor.
$scope.assignRooms = function(name) {
$scope.people.$child(name).$update({
"room_id": $scope.person.room_id,
"is_in": true
});
}
The app is being called correctly. I can see the scopes when I use Angular JS Batarang. When I click the Assign Rooms button I get the error:
Cannot read property 'room_id' of undefined
from this: $scope.person.room_id.
I am sure it's something obvious I am missing. But any help is greatly appreciated.
Thank You!
You need to use person. You can not access the ng-repeat scope within the function.
<td>
<button type="button"
href=""
class="btn btn-primary"
ng-click="assignRooms(name,person)">Assign Rooms</button>
</td>
$scope.assignRooms = function(name, person) {$scope.assignRooms = function(name) {
$scope.people.$child(name).$update({
"room_id": person.room_id,
"is_in": true
});
}