ng-submit refreshes the page instead of submit [duplicate] - angularjs

This question already has an answer here:
ng-click refreshes the page instead of submit
(1 answer)
Closed 5 years ago.
Hi i have an angular web form which takes input from the user and inserts into the database.I am using jersey-jackson rest web services and hibernate.But when i try to submit the form,the previous page which had the hyperlink to the current page is refreshed and the current page is reloaded again(Loading of previous page is seen in the network log).The url specified in the http request is not even invoked.Following is my code
<div id="main">
<h1>Create Leave</h1>
<form class="form-horizontal" ng-controller="MyAddController" >
<div class="form-group">
<label for="employeeName" class="col-sm-3 control-label">Employee Name</label>
<div class="col-sm-6">
<input type="text" id="num" class="form-control" ng-model="num" />
</div>
<div class="col-sm-3"></div>
</div>
<div class="form-group">
<label for="leaveType" class="col-sm-3 control-label">Leave Type</label>
<div class="col-sm-2">
<select id="leaveType" class="form-control" ng-model="leaveType">
<option value="">Hospital</option>
<option value="female">leave type 2</option>
<option value="female">leave type 3</option>
<option value="female">leave type 4</option>
<option value="female">leave type 5</option>
<option value="female">leave type 6</option>
</select>
</div>
<div class="col-sm-7"></div>
</div>
<div class="form-group">
<label for="leaveStartDate" class="col-sm-3 control-label">Leave Start Date</label>
<div class="col-sm-2">
<input type="date" id="startDates" class="form-control" ng-model="startDate" />
</div>
<div class="col-sm-7"></div>
</div>
<div class="form-group">
<label for="leaveEndDate" class="col-sm-3 control-label">Leave End Date</label>
<div class="col-sm-2">
<input type="date" id="endDate" class="form-control" ng-model="endDate" />
</div>
<div class="col-sm-7"></div>
</div>
<div class="form-group">
<div class="col-sm-3"></div>
<div class="col-sm-2">
<span><b>Is Half Day leave</b></span>
<div class="radio">
<label><input value="Yes" type="radio" name="halfDay" ng-model="isHalfDay" />Yes</label>
</div>
<div class="radio">
<label><input value="No" type="radio" name="halfDay" ng-model="isHalfDay" />No</label>
</div>
</div>
</div>
<input type="submit" value="Save" ng-click='add();' class="btn btn-primary col-sm-offset-3" />
<input type="reset" value="Reset" ng-click="resetForm()" class="btn" /> <br/>
</form>
<script>
function MyAddController($scope, $http) {
$scope.add = function() {
$http.get("webapi/blog/create", {
params : {
signum : $scope.num,
leaveType : $scope.leaveType,
startDate : $scope.startDate,
endDate : $scope.endDate,
isHalfDay : $scope.isHalfDay
}
}).success(function(data, status, headers, config) {
if (data) {
$scope.data = data;
alert("success")
}
}).error(function(data, status, headers, config) {
alert("error");
})
}
}
</script>
and the bean class
package com.king.entity;
import java.util.Date;
import javax.persistence.Entity;
import javax.persistence.Id;
#Entity
public class LeaveDetails {
#Id
private String num;
public String getnum() {
return num;
}
public void setnum(String num) {
this.num = num;
}
public String getLeaveType() {
return leaveType;
}
public void setLeaveType(String leaveType) {
this.leaveType = leaveType;
}
public Date getStartdate() {
return startdate;
}
public void setStartdate(Date startdate) {
this.startdate = startdate;
}
public Date getEndDate() {
return endDate;
}
public void setEndDate(Date endDate) {
this.endDate = endDate;
}
public String getIsHalfDay() {
return isHalfDay;
}
public void setIsHalfDay(String isHalfDay) {
this.isHalfDay = isHalfDay;
}
private String leaveType;
private Date startdate;
private Date endDate;
private String isHalfDay;
}
DAO
package com.king.dao;
import java.util.Date;
import java.util.List;
import org.hibernate.Query;
import org.hibernate.Session;
import org.hibernate.Transaction;
import com.king.entity.Blog;
import com.king.entity.LeaveDetails;
import com.king.test.HibernateTest;
public class AddLeaveDao {
public void addDetails(LeaveDetails data) {
Session session = HibernateTest.getSession();
Transaction ts = session.beginTransaction();
session.saveOrUpdate(data);
session.flush();
ts.commit();
session.close();
}
and the WS
package com.king.webapi;
import java.util.Collection;
import java.util.Iterator;
import java.util.List;
import javax.ws.rs.BeanParam;
import javax.ws.rs.GET;
import javax.ws.rs.Path;
import javax.ws.rs.Produces;
import javax.ws.rs.QueryParam;
import com.king.dao.AddLeaveDao;
import com.king.dao.BlogDao;
import com.king.dao.LeaveDao;
import com.king.entity.Blog;
import com.king.entity.LeaveBalance;
//import com.king.entity.Love;
import com.king.entity.LeaveDetails;
#Path("/blog")
public class BlogWS {
#GET
#Path("list")
#Produces({ "application/json" })
public List<LeaveBalance> list() {
List l= new LeaveDao().getAllLeaves();
Iterator i=l.iterator();
while(i.hasNext())
{
LeaveBalance m=(LeaveBalance)i.next();
System.out.println(m.getLeaveBalance());
}
return l;
}
#GET
#Path("create")
#Produces({ "application/json" })
public String create(#BeanParam LeaveDetails ld) {
System.out.println("Entered here");
new AddLeaveDao().addDetails(ld);
System.out.println("Returned here");
return "{}";
}
#GET
#Path("findById")
#Produces({ "application/json" })
public Blog findById(#QueryParam("id") String id) {
return new BlogDao().findBlogById(id);
}
#GET
#Path("update")
#Produces({ "application/json" })
public String update(#BeanParam Blog blog) {
new BlogDao().updateBlog(blog);
return "{}";
}
}
edit:actual js i am using
var app = angular.module('myApp', ['ui.calendar','ui.router']);
app.controller('myNgController', ['$scope', '$http', 'uiCalendarConfig', function ($scope, $http, uiCalendarConfig) {
$scope.SelectedEvent = null;
var isFirstTime = true;
$scope.events = [];
$scope.eventSources = [$scope.events];
$scope.events.push({
title: "Leave",
description: "jahsojoaisjjoijaso",
start: new Date("2017-05-03"),
end: new Date("2017-05-03"),
allDay : false,
stick: false
});
/*//Load events from server
$http.get('/home/getevents', {
cache: true,
params: {}
}).then(function (data) {
$scope.events.slice(0, $scope.events.length);
angular.forEach(data.data, function (value) {
});
});*/
//configure calendar
$scope.uiConfig = {
calendar: {
height: 450,
editable: false,
displayEventTime: false,
header: {
left: 'month basicWeek basicDay agendaWeek agendaDay',
center: 'title',
right:'today prev,next'
},
eventClick: function (event) {
$scope.SelectedEvent = event;
},
eventAfterAllRender: function () {
if ($scope.events.length > 0 && isFirstTime) {
//Focus first event
uiCalendarConfig.calendars.myCalendar.fullCalendar('gotoDate', $scope.events[0].start);
isFirstTime = false;
}
}
}
};
}]);
app.controller("MyDbController",function ($scope, $http) {
//$scope.data = [{title: 'welcome hello'},{title: 'great testing'}];
$http.get("webapi/blog/list", {}).success(function(data, status, headers, config) {
$scope.data = data;
}).error(function(data, status, headers, config) {
alert("error");
})
});
app.controller("MyAddController",function ($scope, $http) {
$scope.add = function() {
$http.get("webapi/blog/create", {
params : {
signum : $scope.num,
leaveType : $scope.leaveType,
startDate : $scope.startDate,
endDate : $scope.endDate,
isHalfDay : $scope.isHalfDay
}
}).success(function(data, status, headers, config) {
if (data) {
$scope.data = data;
alert("success");
}
}).error(function(data, status, headers, config) {
alert("error");
})
}
});
app.config(function($stateProvider){
$stateProvider
.state("applyLeave",{
url:"/applyLeave",
templateUrl:"html/LeaveApply.html",
controller:"leaveController",
controllerAs:"leaveController"
});
v.controller("leaveController",function($scope)
{
})
});
When i click on save this is the url pattern shown in the browser. http://localhost:8081/hibernate-jersey-angularjs/?halfDay=No#/applyLeave .I dont understand why .On running http://localhost:8081/hibernate-jersey-angularjs/webapi/blog/create with dummy parameters everything works fine.But on submit i dont think the webservice is not being called.
Please help

Try putting ng-submit="add()" on your <form> element and remove the ng-click from your submit button.
As things stand I don't think that Angular is intercepting the form post and you're just posting form values to the current URL...

Related

Proceed to another view on button click AngularJS

I have a drop down which is displaying data from a Web API. The data is shown below
here's the code for the drop down
<select ng-model="details" ng-options="x.Name for x in customers"></select>
then I have a text box and a button:
<input type="password" ng-model="pin" ng-required="true"/>
<button ng-click="pinForm.$valid && (count = count + 1)" ng-init="count=0">Proceed</button>
Now there are 2 things I want to implement:
with details.PIN I get the PIN of the selected person in the drop down. What I want to do is on button click to check if the pin entered in the text box match to details.PIN; if so, proceed to another view
I have implemented a count on the button. If the count reach to 3 and the pin entered is wrong, I need to show an error message.
The HTML for the only view I have till now
<body ng-app="customerApp">
<div ng-controller="CustomerCtrl" align="center">
<select ng-model="details" ng-options="x.Name for x in customers"></select>
<h1>you selected {{details.Name}}</h1>
<p>his card status is {{details.cardStatus}}</p>
<hr>
<div ng-switch="details.cardStatus">
<div ng-switch-when="0">
<form name="pinForm">
<input type="password" ng-model="pin" ng-required="true"/>
<p><button ng-click="pinForm.$valid && (count = count + 1)" ng-init="count=0">Proceed</button></p>
<p><span>Attempts left: {{3-count}}</span></p>
</form>
</div>
<div ng-switch-when="1">
<p>This card has been reported as stolen and will be retained. If it is yours, please contact your nearest branch</p>
</div>
<div ng-switch-when="2">
<p>This card has been reported as lost and will be retained. If it is yours, please contact your nearest branch</p>
</div>
</div>
</div>
</body>
</html>
Here is the code for the API
namespace test.Controllers
{
[RoutePrefix("Customer")]
public class CustomerController : ApiController
{
[Route("CustomerRecords")]
public List<Customer> Get()
{
return new List<Customer>()
{
new Customer { CID=1, Name="Bruce Wayne", PIN="1234", Bal=1000000, cardStatus= "0" }
,new Customer { CID=2, Name="Steve Rogers", PIN="2246", Bal=900000, cardStatus= "0" }
,new Customer { CID=3, Name="Jon Snow", PIN="2398", Bal=3000, cardStatus= "1" }
,new Customer { CID=4, Name="Rustin Cohle", PIN="7549", Bal=450000, cardStatus= "2" }
//NOTE
//cardStatus '0' :valid
//cardStatus '1' :stolen
//cardStatus '2' :lost
};
}
}
public class Customer
{
public int CID { get; set; }
public string Name { get; set; }
public string PIN { get; set; }
public int Bal { get; set; }
public string cardStatus { get; set; }
}
}
here's the module, the service and the factory method the code for routing the views:
var customerAppModule = angular.module("customerApp", []);
customerAppModule.controller('CustomerCtrl', function ($scope, CustomerService)
{
getCustomerRecords();
function getCustomerRecords() {
CustomerService.getCustomers()
.success(function (data) {
console.log(data);
$scope.customers = data;
})
.error(function (data, status) {
console.error('failure loading the customer record', status, data);
$scope.customers = {};
});
}
});
customerAppModule.factory('CustomerService', ['$http', function ($http) {
var customerService = {};
var urlBase = 'http://localhost:51701/Customer';
customerService.getCustomers = function () {
return $http.get(urlBase + '/CustomerRecords');
};
return customerService;
}]);
var app = angular.module('routeApp', ['ngRoute']);
app.config(function ($routeProvider) {
$routeProvider
.when('/', {
templateUrl: 'Views/Home/index.cshtml',
controller: 'CustomerCtrl'
})
.when('/MainMenu', {
templateUrl: 'Views/Home/MainMenu.cshtml',
controller: 'CustomerCtrl'
})
});
I'm not sure I've written the code for the routing correctly.
What if you change the ng-click logic, to consums a function instead an expression.
Example
HTML
<body ng-controller="MainCtrl as vm">
<select ng-model="vm.details" ng-options="x.Name for x in vm.customers">
<option value="">Select...</option>
</select>
<h1>you selected {{vm.details.Name}}</h1>
<p>his card status is {{vm.details.cardStatus}}</p>
<hr>
<div ng-switch="vm.details.cardStatus">
<div ng-switch-when="0">
<form name="vm.pinForm">
<input type="password" ng-model="vm.pin" ng-required="true"/>
<p><button ng-disabled="vm.count >=3" ng-click="vm.pinFormCheck();" ng-init="vm.count=0">Proceed</button></p>
<p><span>Attempts left: {{3-vm.count}}</span></p>
</form>
</div>
<div ng-switch-when="1">
<p>This card has been reported as stolen and will be retained. If it is yours, please contact your nearest branch</p>
</div>
<div ng-switch-when="2">
<p>This card has been reported as lost and will be retained. If it is yours, please contact your nearest branch</p>
</div>
<div ng-if="vm.failPin">
<p>Invalid Pin</p>
</div>
<div ng-if="vm.count >=3">
<p>Not Enoguh Attempts</p>
</div>
</div>
</body>
CONTROLLER
var vm = this;
vm.customers = [
{CID:1, Name:'Bruce Wayne', PIN: '1234', Bal: 10000, cardStatus: '0'},
{CID:2, Name:'Steve Rogers', PIN: '2246', Bal: 90000, cardStatus: '0'},
{CID:3, Name:'Jon Snow', PIN: '2398', Bal: 30000, cardStatus: '1'},
{CID:4, Name:'Rustin Cohle', PIN: '7549', Bal: 45000, cardStatus: '2'}
];
vm.pinFormCheck = function(){
vm.count++;
if(vm.pinForm.$valid && (vm.details.PIN === vm.pin) && (vm.count <= 2)){
console.log('all good'); //change location.
}else{
vm.failPin = true;
console.log('atemps', vm.count);
}
};
Working Example in this HERE
Hope this example is good enough for your UNIT CASE

Angular ui-calendar auto refresh on form submission

i am using angular ui-calendar for displaying a series of leaves.The data for this is fed from the REST services.I can add a leave to the database also.The problem is that when i add a leave detail to the database it does not automatically reflect in the calendar.If i refresh the page the data will be reflected. Basically what I want to do is when I submit the form (closing the modal) the data to be displayed in the calendar. Thank you in advance.Following is my code
My controller
app.factory('calendarSer', ['$http', '$rootScope', 'uiCalendarConfig', function($http, $rootScope, uiCalendarConfig) {
return {
displayCalendar: function($scope) {
$http.get("rest/leave/holidayList", {}).success(function(data, status, headers, config) {
$scope.holidayList = data;
$calendar = $('[ui-calendar]');
var date = new Date(),
d = date.getDate(),
m = date.getMonth(),
y = date.getFullYear();
$scope.changeView = function(view) {
$calendar.fullCalendar('changeView', view);
};
var m = null;
if ($scope.selectable == "Yes") {
m = true;
} else {
m = false;
}
/* config object */
$scope.uiConfig = {
calendar: {
lang: 'da',
height: 400,
editable: true,
selectable: m,
header: {
left: 'month basicWeek basicDay',
center: 'title',
right: 'today prev,next'
},
eventClick: function(date, jsEvent, view) {
$scope.alertMessage = (date.title + ' was clicked ');
alert("clicked" + date.title);
},
select: function(start, end, allDay) {
var obj = {};
obj.startDate = start.toDate();
obj.endDate = moment(end - 1 * 24 * 3600 * 1000).format('YYYY-MM-DD');
$rootScope.selectionDate = obj;
$("#modal1").openModal();
// calendar.fullCalendar('unselect');
},
dayRender: function(date, cell) {
var today = new Date();
today = moment(today).toDate();
var end = new Date();
end = moment(end).toDate();
end.setDate(today.getDate() + 7);
date = moment(date).toDate();
angular.forEach($scope.holidayList, function(value) {
if (((moment(value.holiday_date).format("YYYY-MM-DD")) == moment(date).format("YYYY-MM-DD"))) {
cell.css("background-color", "#2bbbad");
//$('.date').text('Today');
cell.prepend("<span style=\"max-width:200px;word-wrap:break-word;margin-top:10px;\">" + value.description + "</span>");
cell.prepend("<br>")
}
});
},
eventRender: $scope.eventRender,
}
};
console.log($scope.holidayList);
}).error(function(data, status, headers, config) {
alert("error from holidaylist");
});
$scope.events = [];
$scope.eventSources = [$scope.events];
$http.get($scope.url, {
cache: true,
params: {}
}).then(function(data) {
console.log(data);
$scope.events.slice(0, $scope.events.length);
angular.forEach(data.data, function(value) {
console.log(value.title);
if (value.approvalStatus == "Approved") {
var k = '#114727';
} else {
k = '#b20000'
}
$scope.events.push({
title: value.signum,
description: value.signum,
start: value.startDate,
end: value.endDate,
allDay: value.isHalfDay,
stick: true,
status: value.approvalStatus,
backgroundColor: k
});
});
});
}
}
}]);
g-include
<div id="controllerid">
<div class="row" >
<div class="col s10 m10 l10">
<div id="calendar" ui-calendar="uiConfig.calendar" ng-model="eventSources" calendar="myCalendar"></div>
</div>
</div>
<!-- Modal Structure -->
<div id="modal1" class="modal" ng-controller="MyAddController">
<div class="modal-content">
<h4>Apply Leave</h4>
<div class="row">
<form class="col s12" id="form1">
<div class="row modal-form-row">
<div class="input-field col s6">
<input id="num" type="text" class="validate" ng-model="test.num"> <label for="num">num</label>
</div>
<div class="input-field col s6">
<input id="ename" type="text" class="validate" ng-model="test.title"> <label for="ename">Employee Name</label>
</div>
</div>
<div class="row">
<form class="col s12">
<div class="row modal-form-row">
<div class="input-field col s5">
<input id="startDate" type="text" class="validate" value="{{selectionDate.startDate | date}}" readonly >
</div>
<div class="input-field col s5">
<input id="endDate" type="text" class="validate" value="{{selectionDate.endDate | date}}" readonly>
</div>
<div class="input-field col s1">
<p>
<input type="checkbox" id="test6" ng-model="test.isHalfDay" /> <label for="test6">Half Day</label>
</p>
</div>
</div>
<div class="row">
<div class="input-field col s12">
<input id="description" type="text" class="validate" ng-model="test.description"> <label for="description">Description</label>
</div>
</div>
</form>
</div>
</div>
<div class="modal-footer">
<button class="btn waves-effect waves-light" type="submit" ng-click="add()" name="action"> Submit <i class="material-icons right">send</i>
</button>
</div>
</div>
and my add controller
app.controller("MyAddController", function($scope, $http,$rootScope,calendarSer) {
$scope.test = {};
$scope.add = function() {
$("#modal1").closeModal();
$scope.test1=$rootScope.selectionDate;
var jsonData = JSON.stringify($.extend({}, $scope.test, $scope.test1));
console.log(""+jsonData);
$http({
url: "rest/leave/create",
method: "POST",
data: jsonData,
headers: {'Content-Type': 'application/json'}
}).success(function(data, status, headers, config) {
if (data) {
console.log("Entered in the add controller");
$scope.data = data;
$scope.url="rest/leave/list";
$scope.selectable="Yes";
calendarSer.displayCalendar($scope);
$("#popupmodal").openModal();
console.log("Exited in the add controller");
}
}).error(function(data, status, headers, config) {
alert("error from create leave");
})
}
});
ANy help would be appreciated
In your "success" function after you run the "create" function, you can simply add the event to fullCalendar using the same data, via the built-in "renderEvent" function.
Something like this (I don't know Angular, so you may need to adjust this slightly to get your calendar element into context, but hopefully you understand the idea). I am also assuming that jsonData contains all the relevant event data which we can use for this:
.success(function(data, status, headers, config) {
if (data) {
console.log("Entered in the add controller");
$scope.data = data;
//add the event to the calendar UI without refreshing the events
$('[ui-calendar]').fullCalendar("renderEvent",
{
start: jsonData.startDate,
end: jsonData.endDate,
title: jsonData.title
},
true //make it stick even when the view changes
);
$scope.url="rest/leave/list";
$scope.selectable="Yes";
calendarSer.displayCalendar($scope);
$("#popupmodal").openModal();
console.log("Exited in the add controller");
}
You may need to add more fields, or you may need to get momentJS to parse the values in startDate / endDate, depending exactly what those fields output.
The "renderEvent" method can be found in the fullCalendar documentation here: https://fullcalendar.io/docs/event_rendering/renderEvent/

ng-click refreshes the page instead of submit

Hi i have an angular web form which takes input from the user and inserts into the database.I am using jersey-jackson rest web services and hibernate.But when i try to submit the form,the previous page which had the hyperlink to the current page is refreshed and the current page is reloaded again(Loading of previous page is seen in the network log).The url specified in the http request is not even invoked.Following is my code
<div id="main">
<h1>Create Leave</h1>
<form class="form-horizontal" ng-controller="MyAddController" >
<div class="form-group">
<label for="employeeName" class="col-sm-3 control-label">Employee Name</label>
<div class="col-sm-6">
<input type="text" id="num" class="form-control" ng-model="num" />
</div>
<div class="col-sm-3"></div>
</div>
<div class="form-group">
<label for="leaveType" class="col-sm-3 control-label">Leave Type</label>
<div class="col-sm-2">
<select id="leaveType" class="form-control" ng-model="leaveType">
<option value="">Hospital</option>
<option value="female">leave type 2</option>
<option value="female">leave type 3</option>
<option value="female">leave type 4</option>
<option value="female">leave type 5</option>
<option value="female">leave type 6</option>
</select>
</div>
<div class="col-sm-7"></div>
</div>
<div class="form-group">
<label for="leaveStartDate" class="col-sm-3 control-label">Leave Start Date</label>
<div class="col-sm-2">
<input type="date" id="startDates" class="form-control" ng-model="startDate" />
</div>
<div class="col-sm-7"></div>
</div>
<div class="form-group">
<label for="leaveEndDate" class="col-sm-3 control-label">Leave End Date</label>
<div class="col-sm-2">
<input type="date" id="endDate" class="form-control" ng-model="endDate" />
</div>
<div class="col-sm-7"></div>
</div>
<div class="form-group">
<div class="col-sm-3"></div>
<div class="col-sm-2">
<span><b>Is Half Day leave</b></span>
<div class="radio">
<label><input value="Yes" type="radio" name="halfDay" ng-model="isHalfDay" />Yes</label>
</div>
<div class="radio">
<label><input value="No" type="radio" name="halfDay" ng-model="isHalfDay" />No</label>
</div>
</div>
</div>
<input type="submit" value="Save" ng-click='add();' class="btn btn-primary col-sm-offset-3" />
<input type="reset" value="Reset" ng-click="resetForm()" class="btn" /> <br/>
</form>
<script>
function MyAddController($scope, $http) {
$scope.add = function() {
$http.get("webapi/blog/create", {
params : {
signum : $scope.num,
leaveType : $scope.leaveType,
startDate : $scope.startDate,
endDate : $scope.endDate,
isHalfDay : $scope.isHalfDay
}
}).success(function(data, status, headers, config) {
if (data) {
$scope.data = data;
alert("success")
}
}).error(function(data, status, headers, config) {
alert("error");
})
}
}
</script>
and the bean class
package com.king.entity;
import java.util.Date;
import javax.persistence.Entity;
import javax.persistence.Id;
#Entity
public class LeaveDetails {
#Id
private String num;
public String getnum() {
return num;
}
public void setnum(String num) {
this.num = num;
}
public String getLeaveType() {
return leaveType;
}
public void setLeaveType(String leaveType) {
this.leaveType = leaveType;
}
public Date getStartdate() {
return startdate;
}
public void setStartdate(Date startdate) {
this.startdate = startdate;
}
public Date getEndDate() {
return endDate;
}
public void setEndDate(Date endDate) {
this.endDate = endDate;
}
public String getIsHalfDay() {
return isHalfDay;
}
public void setIsHalfDay(String isHalfDay) {
this.isHalfDay = isHalfDay;
}
private String leaveType;
private Date startdate;
private Date endDate;
private String isHalfDay;
}
DAO
package com.king.dao;
import java.util.Date;
import java.util.List;
import org.hibernate.Query;
import org.hibernate.Session;
import org.hibernate.Transaction;
import com.king.entity.Blog;
import com.king.entity.LeaveDetails;
import com.king.test.HibernateTest;
public class AddLeaveDao {
public void addDetails(LeaveDetails data) {
Session session = HibernateTest.getSession();
Transaction ts = session.beginTransaction();
session.saveOrUpdate(data);
session.flush();
ts.commit();
session.close();
}
and the WS
package com.king.webapi;
import java.util.Collection;
import java.util.Iterator;
import java.util.List;
import javax.ws.rs.BeanParam;
import javax.ws.rs.GET;
import javax.ws.rs.Path;
import javax.ws.rs.Produces;
import javax.ws.rs.QueryParam;
import com.king.dao.AddLeaveDao;
import com.king.dao.BlogDao;
import com.king.dao.LeaveDao;
import com.king.entity.Blog;
import com.king.entity.LeaveBalance;
//import com.king.entity.Love;
import com.king.entity.LeaveDetails;
#Path("/blog")
public class BlogWS {
#GET
#Path("list")
#Produces({ "application/json" })
public List<LeaveBalance> list() {
List l= new LeaveDao().getAllLeaves();
Iterator i=l.iterator();
while(i.hasNext())
{
LeaveBalance m=(LeaveBalance)i.next();
System.out.println(m.getLeaveBalance());
}
return l;
}
#GET
#Path("create")
#Produces({ "application/json" })
public String create(#BeanParam LeaveDetails ld) {
System.out.println("Entered here");
new AddLeaveDao().addDetails(ld);
System.out.println("Returned here");
return "{}";
}
#GET
#Path("findById")
#Produces({ "application/json" })
public Blog findById(#QueryParam("id") String id) {
return new BlogDao().findBlogById(id);
}
#GET
#Path("update")
#Produces({ "application/json" })
public String update(#BeanParam Blog blog) {
new BlogDao().updateBlog(blog);
return "{}";
}
}
edit:actual js i am using
var app = angular.module('myApp', ['ui.calendar','ui.router']);
app.controller('myNgController', ['$scope', '$http', 'uiCalendarConfig', function ($scope, $http, uiCalendarConfig) {
$scope.SelectedEvent = null;
var isFirstTime = true;
$scope.events = [];
$scope.eventSources = [$scope.events];
$scope.events.push({
title: "Leave",
description: "jahsojoaisjjoijaso",
start: new Date("2017-05-03"),
end: new Date("2017-05-03"),
allDay : false,
stick: false
});
/*//Load events from server
$http.get('/home/getevents', {
cache: true,
params: {}
}).then(function (data) {
$scope.events.slice(0, $scope.events.length);
angular.forEach(data.data, function (value) {
});
});*/
//configure calendar
$scope.uiConfig = {
calendar: {
height: 450,
editable: false,
displayEventTime: false,
header: {
left: 'month basicWeek basicDay agendaWeek agendaDay',
center: 'title',
right:'today prev,next'
},
eventClick: function (event) {
$scope.SelectedEvent = event;
},
eventAfterAllRender: function () {
if ($scope.events.length > 0 && isFirstTime) {
//Focus first event
uiCalendarConfig.calendars.myCalendar.fullCalendar('gotoDate', $scope.events[0].start);
isFirstTime = false;
}
}
}
};
}]);
app.controller("MyDbController",function ($scope, $http) {
//$scope.data = [{title: 'welcome hello'},{title: 'great testing'}];
$http.get("webapi/blog/list", {}).success(function(data, status, headers, config) {
$scope.data = data;
}).error(function(data, status, headers, config) {
alert("error");
})
});
app.controller("MyAddController",function ($scope, $http) {
$scope.add = function() {
$http.get("webapi/blog/create", {
params : {
signum : $scope.num,
leaveType : $scope.leaveType,
startDate : $scope.startDate,
endDate : $scope.endDate,
isHalfDay : $scope.isHalfDay
}
}).success(function(data, status, headers, config) {
if (data) {
$scope.data = data;
alert("success");
}
}).error(function(data, status, headers, config) {
alert("error");
})
}
});
app.config(function($stateProvider){
$stateProvider
.state("applyLeave",{
url:"/applyLeave",
templateUrl:"html/LeaveApply.html",
controller:"leaveController",
controllerAs:"leaveController"
});
v.controller("leaveController",function($scope)
{
})
});
When i click on save this is the url pattern shown in the browser. http://localhost:8081/hibernate-jersey-angularjs/?halfDay=No#/applyLeave .I dont understand why
Please help
Easiest way to fix this is to remove type="submit" from your button that calls the add() method, replacing it with type="button"
<input type="button" value="Save" ng-click='add()' class="btn btn-primary col-sm-offset-3" />
Otherwise, you need to add ng-submit="add()" on your form, and then remove the ng-click="add()" from your button with type=submit.
Your form should look like this:
<form class="form-horizontal" ng-controller="MyAddController" ng-submit="add()">
And your button like this:
<input type="submit" value="Save" class="btn btn-primary col-sm-offset-3" />
Either of these should work.
By the way, you don't need to use ; at the end of an ng-click instruction. Also, try using the button tag instead of input for the save button.
EDIT: You forgot to declare the app to use in your html. On the body of your HTML code, use ng-app='myApp'

how to redirect to other page when request is made using angularjs to spring controller

#MY Login page code snippet
--------------------------------
<div class="login-container">
<form ng-submit="onLogin()" name="form" class="pure-form login-form"
ng-controller="LoginCtrl as vm">
<fieldset class="pure-group">
<legend>Log In</legend>
<label for="inputUsername" class="sr-only">Username</label> <input type="text" id="inputUsername" class="form-control"
placeholder="Username" required autofocus ng-model="vm.username">
<label for="inputPassword" class="sr-only">Password</label> <br>
<input type="password" id="inputPassword" class="form-control"
placeholder="Password" required ng-model="vm.password">
</fieldset>
<button type="submit"
class="pure-button pure-input-1 pure-button-primary">Log In</button>
<div class="alert alert-danger" role="alert" ng-show="errorMsg">{{errorMsg}}</div>
</form>
</div>
<div id="content" class="col-lg-10 col-sm-10">
<div class="row">
<div class="box col-md-12">
<div class="box-inner"></div>
</div>
</div>
</div>
# login.js
-----------------
angular.module('loginApp', [])
.controller('LoginCtrl', ['$scope', '$http', function ($scope, $http) {
$scope.onLogin = function () {
var encodedString = '?username=' +
encodeURIComponent($scope.vm.username) +
'&password=' +
encodeURIComponent($scope.vm.password);
var url = "http://localhost:8080/servicesummary/employees/view"+encodedString;
$http({
method: 'GET',
url: url
})
.success(function(data) {
//alert(JSON.stringify(data));
var container = 'box-inner';
$('.' + container).html(response);
})
.error(function(data) {
$scope.$error = 'Unable to submit form';
})
};
}]);
# Spring Controller-
--------------------------
#RequestMapping(value = "/view", method = RequestMethod.GET, produces = "application/json")
public ModelAndView getEmployeeInJSON(#RequestParam("username") String username, #RequestParam("password") String password) {
final ModelAndView mv = new ModelAndView();
try {
AppUserDTO appUserdb = userService.getObject(username);
if (null != appUserdb && (appUserdb.getPassword() != null)) {
String decodedPass = UtilityService.decode(appUserdb.getPassword());
if (decodedPass.equals(password)) {
System.out.println("Database Match.............");
mv.setViewName(VIEWNAME_HOME);
} else {
mv.setViewName(VIEWNAME_LOGIN);
}
} else {
mv.addObject("uNameNotValid", false);
mv.setViewName(VIEWNAME_LOGIN);
}
} catch (Exception e) {
logger.error("ERROR handleGetLogin() {}", e);
System.out.println("Exception is occured.....");
return new ModelAndView("redirect:/home-exception");
}
return mv;
}
Hi i have user input username and password which i trying to validate from database using spring controller (TestController.java) from angularjs. i am bale to call controller using login.js written, but not able to process the ModelAndView object returned using angularjs. please see my login.js for reference.
You can update your $http method as below
$http({
method: 'GET',
url: url
})
.success(function(data) {
//alert(JSON.stringify(data));
$window.location.href = 'SuccessUrl';
})
.error(function(data) {
$scope.$error = 'Unable to submit form';
})

CheckBox function for same ss billing sddress

i know its very common and very easy thing but really i m very new to angularjs and need your help
My View Page:
<div ng-controller="AddressController">
<div class="form-part-title" ng-show="Caption">{{Caption}} <span ng-show="showSameAsBilling" class="spancheck"><input type="checkbox" id="SameAsBilling" ng-model="Address.SameAsBilling"><label class=" after">Same As Billing Address</label></span> </div>
<div ng-show="!readOnly">
<label class="required">#Resource.Country<span ng-show="showInvalidAddress" class="spancheck"><input type="checkbox" id="InvalidAddress" ng-model="Address.InvalidAddress"><label class="after">Invalid Address</label></span>
<span ng-show="showPostalOnly" class="spancheck"><input type="checkbox" id="PostalOnly" ng-model="Address.PostalOnly"><label class="after">Postal Only</label></span>
</label>
<select kendo-drop-down-list class="sdk-dropdown" ng-model="Address.CountryId" k-options="countries" k-on-change="onChange(kendoEvent)" />
<label>#Resource.Address</label>
<input class="block" type="text" name="Address" ng-model="Address.Address1" maxlength="100" />
<input class="block" type="text" ng-model="Address.Address2" maxlength="100" />
<input class="block" type="text" ng-model="Address.Address3" maxlength="100" />
<label id="lblState">{{StateLabel}}</label>
<select kendo-drop-down-list class="sdk-dropdown" ng-model="Address.StateProvinceId" k-options="states" k-rebind="states" />
<label>#Resource.City</label>
<input class="block" type="text" name="City" ng-model="Address.City" maxlength="50" />
<label>{{ZipCodeLabel}}</label>
<input class="block" type="text" name="ZipCode" ng-model="Address.ZipCode" maxlength="50" />
</div>
<div ng-show="readOnly">
<textarea style="min-height:120px!important" disabled>{{Address.Address}}{{Address.Address1}}
{{Address.Address2}}
{{Address.City}}
{{Address.State}}{{Address.CountryName}}
{{Address.ZipCode}}</textarea>
</div>
</div>
My Angular Controller:
var AddressController = function ($scope, $http, $routeParams, $location) {
$scope.StateLabel = "State";
$scope.ZipCodeLabel = "Zip Code";
$scope.countryDataSource = {
transport: {
read: {
dataType: "json",
url: "/ApplicationData/GetCountries",
}
}
};
$scope.countries = {
dataSource: $scope.countryDataSource,
dataTextField: "Name",
dataValueField: "Id",
optionLabel: "Select..."
};
this.showAlert = function () {
alert("this is test method");
};
$scope.onChange = function (e) {
var countryId = e.sender.value();
if (countryId == 2) {
$scope.StateLabel = "Province";
$scope.ZipCodeLabel = "Postal Code";
}
else {
$scope.StateLabel = "State";
$scope.ZipCodeLabel = "Zip Code";
}
$http.get('/ApplicationData/GetStates/' + countryId).
success(function (jsonData, status, headers, config) {
console.log(jsonData);
var data = {
dataSource: jsonData,
dataTextField: "Name",
dataValueField: "Id",
optionLabel: "Select..."
};
$scope.states = data;
}).
error(function (data, status, headers, config) {
console.log("error getting countries");
});
};
$scope.SameAsBilling = function (checked) {
alert(1);
if (SameAsBilling.checked = true) {
vmCustomer.BillingAddress = vmCustomer.ShippingAddress
}
};
};
AddressController.$inject = ['$scope', '$http', '$routeParams', '$location'];
i need you guys to help me with the below function
$scope.SameAsBilling = function (checked) {
alert(1);
if (SameAsBilling.checked = true) {
vmCustomer.BillingAddress = vmCustomer.ShippingAddress
}
};
i m tying but don't know why the check box is not talking to controller please help

Resources