AngularJS Http Post Method not working - javascript

I am trying to do a http post into database using AngularJS. My code doesn't shows any error, but my database is not being updated and I can't figure it out why. Here is my code:
//topic-service.js
(function() {
'use strict';
angular.module('topic').factory('topicService', topicServiceFunction);
topicServiceFunction.$inject = [ '$http', '$q' ];
function topicServiceFunction($http, $q) {
var topicService = {
getTopics : getTopics
}
return topicService;
function getTopics(obj) {
console.log('-->topicServiceFunction');
console.log(obj.name);
var deferred = $q.defer();
return $http.post('http://localhost:8080/restapp/api/topic',
JSON.stringify(obj)).then(function(response) {
if (typeof response.data === 'object') {
return response.data;
} else {
return deferred.reject(response.data);
}
}, function(response) {
return deferred.reject(response.data);
});
}
}
}())
//topic-controller.js
(function() {
'use strict';
angular.module('topic').controller('topicController',
topicControllerFunction);
topicControllerFunction.$inject = [ '$scope', 'topicService' ];
function topicControllerFunction($scope, topicService) {
$scope.getTopics = getTopics;
function getTopics(topicId,name,description,categId,userId) {
console.log('-->topictrlFunction');
$scope.topics = [];
var obj={
id:$scope.topicId,
name:$scope.name,
description:$scope.description,
id_category:$scope.categId,
user_id:$scope.userId
}
var promise = topicService.getTopics(obj);
promise.then(function(data) {
if (data != undefined && data != null) {
$scope.topics = data;
} else {
$scope.topics = undefined;
}
}, function(error) {
console.log('error=' + error);
$scope.topics = undefined;
})
topicService.getTopics(obj);
$scope.topics = topicService.getTopics(obj);
}
}
}())
//topic.html
<!DOCTYPE html>
<html lang="en" ng-app="myTopics">
<head>
<meta charset="UTF-8">
<script src="../../../bower_components/angular/angular.js"></script>
<script src="app.js"></script>
<script src="topics/module/topic-module.js"></script>
<script src="topics/controller/topic-controller.js"></script>
<script src="topics/service/topic-service.js"></script>
<title>Topics</title>
</head>
<body>
<div ng-controller="topicController">
<div ng-controller="topicController">
<p>
Topic id: <input type="text" ng-model="topicId">
</p>
<p>
Name: <input type="text" ng-model="name">
</p>
<p>
Description: <input type="text" ng-model="description">
</p>
<p>
Id category: <input type="text" ng-model="categId">
</p>
<p>
User id: <input type="text" ng-model="userId">
</p>
<button ng-click="getTopics(topicId,name,description,categId,userId)">Add
topic</button>
<ul ng-repeat="topic in topics">
<li>{{topic.id}} --{{topic.name}} -- {{topic.description}} --
{{topic.id_category}}--{{topic.user_id}}</li>
</ul>
</div>
</body>
</html>

In your service you use $q but return $http promise, that's counter productive, just return deferred promise:
function getTopics(obj) {
console.log('-->topicServiceFunction');
console.log(obj.name);
var deferred = $q.defer();
var data = JSON.stringify(obj)
$http.post('http://localhost:8080/restapp/api/topic', data)
.then(function(response) {
if (typeof response.data === 'object') {
deferred.resolve(response.data);
} else {
deferred.reject(response.data);
}
})
.catch(function(response) {
return deferred.reject(response.data);
});
return deferred.promise;
}
If it still doesn't work you should try to send urlencoded data and not json :
for this just add this header in your request : headers : {'Content-Type':'application/x-www-form-urlencoded; charset=UTF-8'}
and encode data with $httpParamSerializerJQLike service. (Inject it in your service)
function getTopics(obj) {
console.log('-->topicServiceFunction');
console.log(obj.name);
var deferred = $q.defer();
var data = $httpParamSerializerJQLike(obj);
var config = {
headers : {'Content-Type':'application/x-www-form-urlencoded; charset=UTF-8'}
};
$http.post('http://localhost:8080/restapp/api/topic', data, config)
.then(function(response) {
if (typeof response.data === 'object') {
deferred.resolve(response.data);
} else {
deferred.reject(response.data);
}
})
.catch(function(response) {
return deferred.reject(response.data);
});
return deferred.promise;
}

Related

How do I populate html using angular controller prior to display

I am trying to pre-load data based on ng-controller attributes prior to displaying the html and in turn prior to button click(submit). I am new to angular js and not sure how to accomplish the task.
There will be one question and n number of answer options
May last try is as seen in code but I need to get to the controller other than button click. I need to see the question and possible answers before the html is present.
<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<title></title>
<script src="http://home-dev.kmhp.com/global/js/AngularJS/angularjs.min.1.7.5.js"></script>
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.7.5/angular-route.min.js"></script>
<script src="http://home-dev.kmhp.com/global/js/AngularJS/quick-survey/app.js"></script>
<script src="http://home-dev.kmhp.com/global/js/AngularJS/quick-survey/Controllers/vote.js"></script>
<!--<script src="http://home-dev.kmhp.com/global/js/AngularJS/quick-survey/Controllers/HomePageVoteController.js"></script>-->
<script src="http://home-dev.kmhp.com/global/js/AngularJS/quick-survey/services/vote.js"></script>
<script src="http://home-dev.kmhp.com/global/js/AngularJS/quick-survey/services/route.js"></script>
<script>
// app
var app = angular.module('quickSurveyApp', ["ngRoute"]);
// controller(s)
app.controller("VoteCtrl", ["$scope", "qa", "$location", function ($scope, qa, $location) {
//app.controller("VoteCtrl", ["$scope", "qa", "$location", function ($scope, qa, $location) {
// app.factory("VoteService", ["$scope", "qa", "$location", function ($scope, qa, $location) {
$scope.activeQuestions = qa.activeQuestions;
$scope.records = qa.records;
$scope.QuestionText = qa[0].QuestionText;
$scope.AnswerText = qa[0].AnswerText;
$scope.Answers = qa[0].Answers;
$scope.error = false;
$scope.AddVote = function () {
$scope.error = !!$scope.answer;
}
}]);
// service(s)
app.factory("VoteService", ["$http", "$q", function ($http, $q) {
res.setHeader('Access-Control-Allow-Origin', '*');
var service = {};
//Gets all data for page.
var questionNumber = 0;
service.pageInit = function () {
var deferred = $q.defer();
$http.get('/API/quick-survey/api/Question/GetQuestionsByZone/0').then(function (response) {
deferred.resolve(response.data);
}, function (error) {
console.error(error);
deferred.reject("error");
});
return deferred.promise;
};
return service;
}]);
// route(s)
app.config(["$routeProvider", function ($routeProvider) {
$routeProvider
.when("/", {
templateUrl: "/api-test-pages/Quick Survey/survey.html",
//controller: "VoteCtrl",
controller: "VoteCtrl",
// it's is good to download the data before displaying the template without the data
// so all we found in resolve is gonna be "resolved" before display the page and running the controller
resolve: {
qa: ["VoteService", "$route", function (VoteService, $route) {
return VoteService.pageInit();
}]
}
}).
otherwise({
redirectTo: '/'
});
}]);
</script>
</head>
<body ng-app="quickSurveyApp">
<div>
<h1>Quick Survey</h1>
<div ng-view></div>
</div>
</body>
</html>
var app = angular.module("quickSurveyApp", ["ng-Route"]);
app.config(["$routeProvider", function ($routeProvider) {
//res.setHeader('Access-Control-Allow-Origin', '*');
$routeProvider
.when("/", {
templateUrl: "/api-test-pages/Quick-Survey/survey.html",
//templateUrl: "/API/quick-survey/api-test-pages/Quick Survey/survey.html",
controller: "VoteCtrl",
resolve: {
qa: ["VoteService", "$route", function (VoteService, $route) {
// return VoteService.pageInit(1);
return VoteService.pageInit();
}]
}
})
.when("/question/:q", {
templateUrl: "templates/survey.tpl",
controller: "VoteCtrl",
resolve: {
qa: ["VoteService", "$route", function (VoteService, $route) {
var questionNumberFromURL = $route.current.params.q;
//return VoteService.pageInit(questionNumberFromURL);
return VoteService.pageInit();
}]
}
})
.when("/thanks", {
templateUrl: "templates/home.tpl",
controller: ["$timeout", "$scope", "$location", function ($timeout, $scope, $location) {
$scope.message = "Thank you !!!";
$timeout(function () {
$location.path("/");
}, 3000);
}]
}).
otherwise({
redirectTo: '/xxxx.html'
});
var app = angular.module('quickSurveyApp', ["ngRoute"]);
function SetCookiesForDebugging() {
var thecookie = "departid=351&jobtitle=Digital+Developer&floor=0&username=ij25405&ps%5Fdeptname=Digital+Experience&ps%5Fdeptid=351&cost%5Fcenter=351&birthday%5Fday=16&birthday=0&fsla=&nbsp&psdeptname=Digital+Experience&managerwholename=Lawrence+Raffel&area=215&mailstop=%2D+None+Selected+%2D&managerid=21286&departmentid=0&extension=2158635597&emplid=08636&managerusername=LR22638&deptname=KY+Exec+Dir&cubeoffice%5Fno=+&ismanager=0&email=tmruk%40amerihealthcaritas%2Ecom&lob=1&fname=Timothy&is%5Fuserlive=1&psdeptid=351&url=%23&costcenter=351&lname=Mruk&company=KEY&managerphone=2159378142&is%5Fmanager=0&wholename=Timothy+Mruk&id=13332&building=0&guest="
document.cookie = thecookie;
}
// sets all scope variables based on associate cookie information.
function SetUser($scope) {
//Set User Information with Cookie data
$scope.IsManager = getCookie("ismanager");
$scope.UserId = getCookie("emplid"); //
$scope.FirstName = getCookie("fname");
$scope.LastName = getCookie("lname");
$scope.EmailAddress = getCookie("email");
$scope.UserName = getCookie("username");
}
// loops through iNSIGHT cookie to retrieve specific value.
// removes all HTML characters.
function getCookie(name) {
var cookiesArray = document.cookie.split("&");
for (var i = 0; i < cookiesArray.length; i++) {
var nameValueArray = cookiesArray[i].split("=");
var cookieName = decodeURI(nameValueArray[0]);
var cookieValue = nameValueArray[1].replace(/\+/g, '%20');
cookieValue = decodeURIComponent(cookieValue);
if (cookieName == name) {
return decodeURI(cookieValue);
}
}
}
app.controller("VoteCtrl", function ($scope, $http) {
SetCookiesForDebugging();
SetUser($scope);
$scope.voteRequest = {
VoteId: null,
VoteDate: null,
UserName: $scope.UserName,
VoterFname: $scope.FirstName,
VoterLname: $scope.LastName,
Id: null,
QuestionId: null,
QuestionText: "",
AnswerText: ""
};
//Gets all data for page.
$scope.pageInit = function () {
res.setHeader('Access-Control-Allow-Origin', '*');
$http({
method: 'GET',
url: '/API/quick-survey/api/Question/GetQuestionsbyZone/0'
//*url: 'http://localhost:51230/api/Question/GetQuestionsByZone/0'
}).then(function (response){
$scope.activeQuestions = response.data;
},function (error){
console.log(error);
});
};
// inserts new request
$scope.insertRequest = function () {
$http.post("/API/quick-survey/api/Vote/AddVote", $scope.voteRequest).then(function (data, status, headers, config) {
alert("success");
}, function (data, status, headers, config) {
console.log("error!");
console.log(data);
});
};
// checks if user already voted for a question
$scope.getUserVoteCount = function () {
// get true or false
$http.get("/API/quick-survey/api/Vote/GetUserVoteCount/866/ijohnson/0").success(function (data, status, headers, config) {
$scope.activeQuestions = data;
}).error(function (data, status, headers, config) {
console.log(status);
});
};
//radio button click on request form
$scope.handleAnswerRadioClick = function (data) {
$scope.voteRequest.QuestionId = data.QuestionId;
$scope.voteRequest.Id = data.Id;
$scope.voteRequest.AnswerText = data.AnswerText;
};
});
var app = angular.module('quickSurveyApp', ["ngRoute"]);
app.controller("VoteCtrl", ["$scope","qa","$location", function ($scope, qa, $location) {
SetCookiesForDebugging();
SetUser($scope);
$scope.voteRequest = {
VoteId: null,
VoteDate: null,
UserName: $scope.UserName,
VoterFname: $scope.FirstName,
VoterLname: $scope.LastName,
Id: null,
QuestionId: null,
QuestionText: "",
AnswerText: ""
};
$scope.activeQuestions = qa.activeQuestions;
//*******
$scope.Answers = qa.records;
$scope.error = false;
$scope.AddVote = function () {
if ($scope.answer == undefined)
$scope.error = true;
else {
$scope.error = false;
if (qa.next)
$location.path("question/" + qa.next)
else
$location.path("thanks");
}
}
//radio button click on request form
$scope.handleAnswerRadioClick = function (data) {
$scope.voteRequest.QuestionId = data.QuestionId;
$scope.voteRequest.Id = data.Id;
$scope.voteRequest.AnswerText = data.AnswerText;
};
function SetCookiesForDebugging() {
var thecookie = "departid=351&jobtitle=Digital+Developer&floor=0&username=ij25405&ps%5Fdeptname=Digital+Experience&ps%5Fdeptid=351&cost%5Fcenter=351&birthday%5Fday=16&birthday=0&fsla=&nbsp&psdeptname=Digital+Experience&managerwholename=Lawrence+Raffel&area=215&mailstop=%2D+None+Selected+%2D&managerid=21286&departmentid=0&extension=2158635597&emplid=08636&managerusername=LR22638&deptname=KY+Exec+Dir&cubeoffice%5Fno=+&ismanager=0&email=tmruk%40amerihealthcaritas%2Ecom&lob=1&fname=Timothy&is%5Fuserlive=1&psdeptid=351&url=%23&costcenter=351&lname=Mruk&company=KEY&managerphone=2159378142&is%5Fmanager=0&wholename=Isaac+Johnson&id=22665&building=0&guest="
document.cookie = thecookie;
}
// sets all scope variables based on associate cookie information.
function SetUser($scope) {
//Set User Information with Cookie data
$scope.IsManager = getCookie("ismanager");
$scope.UserId = getCookie("emplid"); //
$scope.FirstName = getCookie("fname");
$scope.LastName = getCookie("lname");
$scope.EmailAddress = getCookie("email");
$scope.UserName = getCookie("username");
}
// loops through iNSIGHT cookie to retrieve specific value.
// removes all HTML characters.
function getCookie(name) {
var cookiesArray = document.cookie.split("&");
for (var i = 0; i < cookiesArray.length; i++) {
var nameValueArray = cookiesArray[i].split("=");
var cookieName = decodeURI(nameValueArray[0]);
var cookieValue = nameValueArray[1].replace(/\+/g, '%20');
cookieValue = decodeURIComponent(cookieValue);
if (cookieName == name) {
return decodeURI(cookieValue);
}
}
}
}]);
app.factory("VoteService", ["$http", "$q", function ($http, $q) {
var service = {};
var urlBase = "API/quick-survey/api";
$scope.pageInit = function () {
// Get Questions from api
res.setHeader('Access-Control-Allow-Origin', '*');
$http({
method: 'GET',
url: '/API/quick-survey/api/Question/GetQuestionsByZone/0'
}).then(function (response) {
$scope.activeQuestions = response.data;
}, function (error) {
console.log(error);
});
};
//Gets all data for page.
service.pageInit = function () {
var deferred = $q.defer();
//res.setHeader('Access-Control-Allow-Origin', '*');
//$http.get(urlBase + '/Question/GetQuestionsByZone/' + questionNumber).then(function (response) {
// $http.get(urlBase + '/Question/GetQuestionsByZone/' + 0).then(function (response) {
$http.get('/API/quick-survey/api/Question/GetQuestionsByZone/0').then(function (response) {
deferred.resolve(response.data);
}, function (error) {
console.error(error);
deferred.reject("error");
});
return deferred.promise;
};
// inserts new request
service.insertRequest = function (questionNumber) {
var deferred = $q.defer();
$http.post(urlBase + '/Vote/AddVote', $scope.voteRequest).then(function (response, status, headers, config) {
console.log(response.data);
deferred.resolve(response.data);
}, function (error) {
console.error(error);
deferred.reject("error");
});
return deferred.promise;
};
// checks if user already voted for a question
service.getUserVoteCount = function (questionNumber) {
var deferred = $q.defer();
// get true or false
$http.get(urlBase + '/Vote/GetUserVoteCount/866/ijohnson/' + questionNumber).success(function (response, status, headers, config) {
deferred.resolve(response.data);
}, function (error) {
console.error(error);
deferred.reject("error");
});
return deferred.promise;
};
return service;
}]);// JavaScript source code
h1>Quick Survey</h1>
<div ng-model="QuestionText">
<!--Question-->
<h2>{{QuestionText}}</h2>
</div>
<!-- <div -->
<div ng-model="AnswerText">
<!--Possible Answers-->
<br ng-repeat-start="a in Answers" />
<input id="button{{a.AnswerText}}" name="selection" value="{{a.AnswerText}}" type="radio" ng-model="$parent.Answer" />
<label for="button{{a.AnswerText}}" ng-repeat-end>{{a.AnswerText}}</label>
</div>
<br />
<br />
<div>
<input id="surveybtn" type="button" value="Vote Now" ng-click="AddVote()" />
</div>

Trying to activate a checkbox from a controller that lives in another controller

I am trying to activate a checkbox from a controller that lives in another controller. For example, I have a card named information technology under a separate controller and when I click this I want it to route to another page that has a checkbox for information technology from another controller and I want it checked as it renders the page.
The application architecture is very lengthy so I wont include any code base here. But I would like to know an approach I can take.
This is the controller where I want the logic to live and to mark a text box as checked (which lives on another controller).
angular
.controller("mycontroller", mycontroller);
mycontroller.$inject = [
"$scope"
];
// getting the getData() data
$scope.getData = function (data, type) {
console.log("whats this data about in getData(data) ", data)
$scope.query = data.name;
if (data.checked == undefined) {
data.checked = true;
}
}
Below: Is the controller where the checkbox controller lives
angular
.controller('supplierIntelligenceCtrl', function ($scope, $q, FetchData, dataStore, SharedService,
$document, $window, $state, $rootScope, $timeout, DataCache,
$filter, $interval, $localStorage, $http) {
$scope.getData = function (data, type) {
console.log("whats this data about in getData(data) ", data)
$scope.query = data.name;
if (data.checked == undefined) {
data.checked = true;
}
}
$scope.apply = function (type) {
$scope.select = false;
$scope.bigres = 0;
$scope.mobFil = 3;
$scope.applyFilter(type);
}
$scope.disableApply = false;
$scope.disableApply2 = false;
$scope.applyFilter = function (type) {
console.log("this is type ", type)
if (type == 'industries') {
$scope.filters.industries = $scope.industries.filter(function (e) {
console.log("this is e ", e.checked)
return e.checked;
}).map(function (f) {
console.log(" this is f >>>> ",
f)
return f.id
})
$scope.filters.countries = [];
if ($scope.countries != undefined) {
$scope.countries = $scope.countries.map(function (e) {
e.checked = false;
return e;
})
}
$scope.filters.cities = [];
if ($scope.cities != undefined) {
$scope.cities = $scope.cities.map(function (e) {
e.checked = false;
return e;
})
}
$scope.start = 0;
if ($scope.filters.industries.length > 0) {
$scope.callBackend();
$scope.disableApply2 = true;
FetchData.fetchDNBCountriesByIndustries('industries=' + $scope.filters.industries + '&size=').then(function (res) {
$scope.disableApply2 = false;
$scope.countries = res.data;
$scope.countriesPage += 10
}, function () {
$scope.disableApply2 = false;
});
} else {
$scope.callBackend();
}
}
if (type == 'countries') {
$scope.filters.countries = $scope.countries.filter(function (e) {
return e.checked;
}).map(function (f) {
return f.id;
})
$scope.filters.cities = [];
if ($scope.cities != undefined) {
$scope.cities = $scope.cities.map(function (e) {
e.checked = false;
return e;
})
}
$scope.start = 0;
if ($scope.filters.countries.length > 0) {
$scope.callBackend();
$scope.disableApply2 = true;
FetchData.fetchDNBCitiesByIndustriesAndCountries('industries=' + $scope.filters.industries + '&countries=' + $scope.filters.countries + '&size=').then(function (res) {
$scope.disableApply2 = false;
$scope.cities = res.data;
}, function () {
$scope.disableApply2 = false;
})
} else {
$scope.callBackend();
}
}
if (type == 'cities') {
$scope.filters.cities = $scope.cities.filter(function (e) {
return e.checked;
}).map(function (f) {
return f.id
})
$scope.start = 0;
$scope.callBackend();
}
if (type == 'classifications') {
$scope.filters.classifications = $scope.classifications.filter(function (e) {
return e.checked;
}).map(function (f) {
return f.statusCode;
})
$scope.start = 0;
$scope.callBackend();
}
}
}
Here is the HTML where the checkbox lives:
<div ng-repeat="data in industries ">
<input id="{{data.id}}in" type="checkbox" aria-invalid="false"
ng-model="data.checked"
ng-change="getData(data,'industry')">
<label for="{{data.id}}in">{{data.name}}</label>
</div>
Maybe Im missing the point here and perhaps am overlooking something. Im new to angularjs and need to implement this capability to route a button/card to another page that checks a checkbox filter.
Please - any advise would be great . :)
Here is an example of controllers sharing an array via a shared service injected by the dependency injector. Check the checkbox in one controller and it shows in the other.
angular.module('app', []);
angular.module('app')
.factory('dataService', [function () {
return {
data: [
{ prop: '1', checked: false },
{ prop: '2', checked: false },
{ prop: '3', checked: false },
{ prop: '4', checked: false }
]
};
}]);
angular.module('app')
.controller('controller1', ['dataService', function (dataService) {
this.data = dataService.data;
}]);
angular.module('app')
.controller('controller2', ['dataService', function (dataService) {
this.data = dataService.data;
}]);
angular.module('app')
.controller('controller3', ['dataService', function (dataService) {
this.toggleAll = () => {
dataService.data.forEach(item => item.checked = !item.checked)
};
}]);
[ng-controller] { display: inline-block; margin-right: 30px; vertical-align: top; }
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.7.2/angular.min.js"></script>
<div ng-app="app">
<div ng-controller="controller1 as ctrl">
<strong>Controller 1</strong>
<div ng-repeat="item in ctrl.data">
<label>Item {{item.prop}} <input type="checkbox" ng-model="item.checked"></label>
</div>
</div>
<div ng-controller="controller2 as ctrl">
<strong>Controller 2</strong>
<div ng-repeat="item in ctrl.data">
<label>Item {{item.prop}} <input type="checkbox" ng-model="item.checked"></label>
</div>
</div>
<div ng-controller="controller3 as ctrl">
<strong>Controller 3</strong>
<div>
<button ng-click="ctrl.toggleAll()">Toggle all</button>
</div>
</div>
</div>
Put industries as a property on a shared service that you inject into both of the controllers by the dependency injector. Then one controller can bind it to it's view and the other one can change the checked properties on them.
Since you are talking about redirection and then checking a check box, you can try either of below options
Send selection 'information technology' in query string to redirected page and check the check box
If you own a back end server then put the value in cookie and read it in your angular js app
Hope this helps.

can not add data in sql server database in angularjs?

I Have simple app in Angularjs and I have little experience in Angularjs.
my question is I can add data in database . I think I have no errors that prevent me from adding that data.
There no errors displayed but the data not send correctly
GoverController
public ActionResult Index(Governorate gov)
{
string message = "";
if (ModelState.IsValid)
{
using (DoctorEntities dc = new Models.DoctorEntities())
{
dc.Governorates .Add(gov);
dc.SaveChanges();
message = "تم اضافة المحافظة";
}
}
else
{
message = "خطا";
}
return new JsonResult { Data = message, JsonRequestBehavior = JsonRequestBehavior.AllowGet };
}
gov.js
(function () {
angular.module('MyApp', [])
.controller('AdminController', function ($scope, RegisterService) {
$scope.submitText = "save";
$scope.submitted = false;
$scope.message = '';
$scope.isFormValid = false;
$scope.gov = {
GovernorateName: ''
};
$scope.$watch('f1.$valid', function (newValue) {
$scope.isFormValid = newValue;
});
$scope.SaveDate = function (data) {
if (submitText == "save") {
$scope.submitted = true;
$scope.message = '';
}
if ($scope.isFormValid==false){
$scope.submitText = "please wait....";
$scope.gov = data;
RegisterService.SaveFoemData($scope.gov).then(function (d) {
alert(d);
if (d == 'success') {clearform(); }$scope.submitText='save';
} );
}
else{
$scope.message='please fill required data';
}
};
function clearform(){
$scope.gov=null;
$scope.f1.$setPristine();
$scope.submitted=false;
}})
.factory('RegisterService', function ($http,$q) {
var fac = {};
fac.SaveFoemData = function (data) {
var defer = $q.defer();
$http({
url: '/Gover/Index',
method: 'get',
data: JSON.stringify(data),
headers: {'content-type':'application/json'}
}).success(function (d) {
defer.resolve(d);
}).error(function (e) {
defer.reject(e);
});
return defer.promise();
}
return fac;
});
})();
AddGov.cshtml
#{
ViewBag.Title = "AddGov";
Layout = "~/Views/Shared/_Layout.cshtml";
}
<h2>AddGov</h2>
<div ng-controller="AdminController">
<form novalidate name="f1" ng-submit="SaveData(gov)">
{{message}}
<table>
<tr>
<td>
<input type="text" ng-model="gov.GovernorateName" name="GovernorateName" ng-class="submitted?'ng-dirty':''" required autofocus />
</td>
</tr>
<tr>
<td><input type="submit" value="{{submitText}}" /></td>
</tr>
</table>
</form>
</div>
#section scripts{
<script src="~/Scripts/MyProject/gov.js"></script>
}
i tried to find solution to this question

#ModelAttribute in my REST comes empty

I am trying to pass data through <select multiple> from HTML to my RESTful.
That data is an array of String. I don't know why when it comes to my backend it's empty.
This is my REST:
#PutMapping("/events")
#Timed
public ResponseEntity<Event> updateEvent(#RequestBody Event event, #ModelAttribute("attendeesToParse") ArrayList<String> attendeesToParse) throws URISyntaxException {
//Some code
}
This is my HTML:
<div class="form-group">
<label>Attendees</label>
<select class="form-control" multiple name="attendeesToParse" ng-model="vm.usernames"
ng-options="customUser as customUser.username for customUser in vm.customusers">
<option value=""></option>
</select>
</div>
I tried to fix this one for days, I googled it so much but I found no solutions. Please help me.
I can not change my HTML into a JSP due to my project's structure and business logic.
Why does it come empty? If I try to show some logs I see an empty array [].
UPDATE
My HTML form call:
<form name="editForm" role="form" novalidate ng-submit="vm.save()">
<!-- some code -->
<div class="modal-footer">
<button type="button" class="btn btn-default" data-dismiss="modal" ng-click="vm.clear()">
<span class="glyphicon glyphicon-ban-circle"></span> <span data-translate="entity.action.cancel">Cancel</span>
</button>
<button type="submit" ng-disabled="editForm.$invalid || vm.isSaving" class="btn btn-primary">
<span class="glyphicon glyphicon-save"></span> <span data-translate="entity.action.save">Save</span>
</button>
</div>
</form>
My event-dialog-controller.js: (is the .js controller that works with form)
(function() {
'use strict';
angular
.module('businessRequestApp')
.controller('EventDialogController', EventDialogController);
EventDialogController.$inject = ['$timeout', '$scope', '$stateParams', '$uibModalInstance', '$q', 'entity', 'Event', 'Desk', 'CustomUser'];
function EventDialogController ($timeout, $scope, $stateParams, $uibModalInstance, $q, entity, Event, Desk, CustomUser) {
var vm = this;
vm.event = entity;
vm.clear = clear;
vm.datePickerOpenStatus = {};
vm.openCalendar = openCalendar;
vm.save = save;
vm.reftables = Desk.query({filter: 'event-is-null'});
$q.all([vm.event.$promise, vm.reftables.$promise]).then(function() {
if (!vm.event.refTable || !vm.event.refTable.id) {
return $q.reject();
}
return Desk.get({id : vm.event.refTable.id}).$promise;
}).then(function(refTable) {
vm.reftables.push(refTable);
});
vm.customusers = CustomUser.query();
$timeout(function (){
angular.element('.form-group:eq(1)>input').focus();
});
function clear () {
$uibModalInstance.dismiss('cancel');
}
function save () {
vm.isSaving = true;
if (vm.event.id !== null) {
Event.update(vm.event, onSaveSuccess, onSaveError);
} else {
Event.save(vm.event, onSaveSuccess, onSaveError);
}
}
function onSaveSuccess (result) {
$scope.$emit('businessRequestApp:eventUpdate', result);
$uibModalInstance.close(result);
vm.isSaving = false;
}
function onSaveError () {
vm.isSaving = false;
}
vm.datePickerOpenStatus.date = false;
function openCalendar (date) {
vm.datePickerOpenStatus[date] = true;
}
}
})();
My event-service.js:
(function() {
'use strict';
angular
.module('businessRequestApp')
.factory('Event', Event);
Event.$inject = ['$resource', 'DateUtils'];
function Event ($resource, DateUtils) {
var resourceUrl = 'api/events/:id';
return $resource(resourceUrl, {}, {
'query': { method: 'GET', isArray: true},
'get': {
method: 'GET',
transformResponse: function (data) {
if (data) {
data = angular.fromJson(data);
data.date = DateUtils.convertLocalDateFromServer(data.date);
}
return data;
}
},
'update': {
method: 'PUT',
transformRequest: function (data) {
var copy = angular.copy(data);
copy.date = DateUtils.convertLocalDateToServer(copy.date);
return angular.toJson(copy);
}
},
'save': {
method: 'POST',
transformRequest: function (data) {
var copy = angular.copy(data);
copy.date = DateUtils.convertLocalDateToServer(copy.date);
return angular.toJson(copy);
}
}
});
}
})();
My event.controller.js:
(function () {
'use strict';
angular
.module('businessRequestApp')
.controller('EventController', EventController);
EventController.$inject = ['Event', 'CustomUser', '$scope'];
function EventController(Event, CustomUser, $scope) {
var vm = this;
vm.events = [];
vm.customUsers = [];
vm.usernames = ["test1", "test2", "test3"];
$scope.allCustomUsers = [];
loadAll();
function loadAll() {
Event.query(function (result) {
vm.events = result;
vm.searchQuery = null;
});
CustomUser.query(function (result) {
vm.customUsers = result;
vm.searchQuery = null;
for (var i = 0; i < vm.customUsers.length; i++) {
$scope.allCustomUsers.push(vm.customUsers[i].username);
}
});
}
}
})();
If you're using angularJS, you can't data bind data with #ModelAttribute, because #ModelAttribute exists only with template engines such as JSP, and AngularJS is not a template engine within Spring. Try instead to use #RequestBody on String parameter, and then extract the data using Jackson.
One more issue, How exactly do you pass your values from front to back? I don't see any $http angularJS call, and no HTML form with POST method.

angular Validate can't be done

I not able to validate my input to the json data whenever i try to compare with json the else block only executed. pls help me to fix this issue.
<body ng-app="fileGetting" ng-controller="loadFile">
<label>Firstname:</label><input type="text" ng-model="placeFile.fname"><br>
<label>Lastname:</label><input type="text" ng-model="placeFile.lname"><br>
<button ng-click="fun()">Submit</button><br>
<div ng-repeat="x in placeFile">
<p>{{x.fname}}</p>
</div>
<script>
angular.module("fileGetting", [])
.controller("loadFile", function($scope, $http) {
$http.get("exam.json").then(function(response) {
$scope.placeFile = response.data.names;
var x = $scope.placeFile;
$scope.fun = function() {
angular.forEach(x, function(value, key) {
if ($scope.placeFile.fname == x.key && $scope.placeFile.lname == x.key)
{
alert("hi ram");
}
else
{
alert("this is incorrect");
}
});
}
});
});
</script>
This is the Json data:
{
"names":[
{
"fname":"Ram",
"lname":"Chandru"
},
{
"fname":"Chandran",
"lname":"Krishna"
},
{
"fname":"Jayanth",
"lname":"Jo"
}
]
}
Eventually i got an answer i would like to thanks Magnus and Simon.
<body ng-app="myApp" ng-controller="loadFile">
<label>Firstname:</label><input type="text" ng-model="current.fname"><br>
<label>Lastname:</label><input type="text" ng-model="current.lname"><br>
<button ng-click="fun()">Submit</button><br>
<script>
angular.module("myApp", [])
.controller("loadFile", function($scope, $http) {
$scope.current = {fname:"", lname:""};
$http.get("exam.json").then(function(response) {
$scope.placeFile = response.data.names;
$scope.fun=function(){
$scope.placeFile.forEach(function(itm) {
if ($scope.current.fname===itm.fname && $scope.current.lname === itm.lname ) {
alert("Hi Ram");
}
});
}
});
});
</script>
If i understand correctly what you are doing the following should work:
First change
<label>Firstname:</label><input type="text" ng-model="placeFile.fname"><br>
<label>Lastname:</label><input type="text" ng-model="placeFile.lname"><br>
to
<label>Firstname:</label><input type="text" ng-model="current.fname"><br>
<label>Lastname:</label><input type="text" ng-model="current.lname"><br>
code should be:
angular.module("myApp", [])
.controller("loadFile", function ($scope, $http) {
$scope.current = { "fname": "", "lname": "" };
$scope.placefile = [];
$http.get("exam.json").then(function (response) {
$scope.placeFile = response.data.names;
});
$scope.fun = function () {
$scope.placeFile.forEach(function (itm) {
if (itm.fname === $scope.current.fname
&& itm.lname === $scope.current.lname) {
alert("Hi Ram");
}
else {
alert("incorrect");
}
});
};
});
Regards
Magnus

Categories

Resources