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'
Related
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/
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...
I am Getting null value in action method when i am pass data from angular js to action method. data is coming up to $scope.custmodel and i debug and see it hit to the AddCutomer method but data is null. can anyone help me to fix this issue
Admin.js code
var app = angular.module("adminmdl", [])
app.controller("admincontroller", function ($scope,AdminService) {
$scope.Action = 'Add';
$scope.data = {
cus_code: '',
cus_name: ''
}
$scope.savecu = function () {
AdminService.saveCustomerDdetails($scope.cusmodel).then(function (data) {
if (data != null) {
alert('Insert successfully');
} else {
alert('error in inerting data');
}
});
}
})
.factory("AdminService", function ($http) {
var fact = {};
fact.saveCustomerDdetails = function (d) {
return $http({
url: '/Admin/AddCutomer',
method: 'POST',
data: JSON.stringify(d),
headers: { 'content-type': 'application/json' }
});
};
return fact;
});
ASP MVC Method
[HttpPost]
public JsonResult AddCutomer(Customer customer) {
te.Customers.Add(customer);
te.SaveChanges();
string message = "Success";
return new JsonResult { Data = message, JsonRequestBehavior = JsonRequestBehavior.AllowGet };
}
html code
<form class="form-horizontal" method="post" action="#" name="basic_validate" id="basic_validate" novalidate="novalidate">
<div class="control-group">
<label class="control-label">Customer Code</label>
<div class="controls">
<input type="text" ng-model="cusmodel.Customercode" name="required" id="required" >
</div>
</div>
<div class="control-group">
<label class="control-label">Customer Name</label>
<div class="controls">
<input type="text" ng-model="cusmodel.Customername" name="name" id="name" >
</div>
</div>
<div class="control-group">
<div class="controls">
<input type="submit" value="Save" ng-click="savecu()" class="btn btn-success">
<input type="submit" value="Clear" class="btn btn-success" />
</div>
</div>
add [FromBody] attribute to the controller as shown below
public JsonResult AddCutomer([FromBody] Customer customer)
#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';
})
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