Here is My html page which is a basic form that has the list of details for scheduling a test
<div class="container panel">
<form ng-submit="submit(testConfigForm)">
<input type="text" name="testName" ng-model="test.testName"> Test Name <br/>
<input type="date" name="testDate" ng-model="testConfigForm.testDate"> Test Date <br/>
<input type="number" min="0" max="100" name="testTargetScore" ng-model="testConfigForm.testScore"> Test Score <br/>
<span ng-repeat="unit in units">
<label><input type="checkbox" name="checkbox" ng-model="testForm.chapters[$index]">{{unit.name}}</label><br>
</span>
<input type="submit" value="Save">
</form>
This is how my controllerlooks like
app.controller('TestConfigurationCtrl', ['$scope', '$routeParams', '$sce', '$http', 'chapterService',
function ($scope, $routeParams, $sce, $http, unitService) {
$scope.chapters = unitService.getUnits();
$scope.postUrl = $sce.trustAsResourceUrl($routeParams.content_item_return_url);
$scope.submit = function(testConfigForm) {
var config = {
"#context" : [],
"#graph" : [ {
"#type" : "ContentItemPlacement",
"placementOf" : {
"#type" : "LtiLink",
"text" : "test",
"mediaType" : "application/vnd.ims.lti.v1.launch+json",
"title" : "Test Exam",
"custom" : {
"name" : testConfigForm.testName,
"dueDate" : testConfigForm.testDate,
"targetScore" : testConfigForm.testTargetScore,
"chapters" : testConfigForm.units
},
"activityType" : "abc",
"activityId" : "1"
}
} ]
};
$http.post($scope.postUrl, config)
.success(function (data, status, headers, config)
{
$scope[resultVarName] = data;
})
.error(function (data, status, headers, config)
{
$scope[resultVarName] = "SUBMIT ERROR";
});
};
}]);
});
How can i post the data from the form. It gives me an error of failed to load resource
I think I found the problem, is this:
$scope.postUrl = $sce.trustAsResourceUrl($routeParams.content_item_return_url);
...
$http.post($scope.postUrl, config)
You shouldn't use $scope.postUrl on post, use the url as is:
var postUrl = $routeParams.content_item_return_url;
$scope.postUrl = $sce.trustAsResourceUrl(postUrl);
...
$http.post(postUrl, config)
Related
Using a factory, I want to get information from one page (text fields and a submit button), put it in an array, and read from that array to post it into a different page. Here is a snippet of my code.
app.factory("service", function(){
var serv = {};
serv.arr = [];
serv.add = (title, name, post, tag) => serv.arr.push({
"title" : title, "name" : name, "post" : post, "tag" : tag
});
return serv;
});
app.controller("createCtrl", ["$scope", "service", function($scope, service)
{
display = () => service.add($scope.title, $scope.name, $scope.post,
$scope.tag);
console.log(service.arr);
}]);
app.controller("newsCtrl", ["$scope", "service", function($scope, service){
$scope.newsPage = "News";
$scope.array = service.arr;
}]);
I know I'm probably way off but at this stage I can't even tell if any information is being added to the array.
Try below code for set & get data from factory.
Click on SAVE DATA & then GET DATA buttons to see the actions
(function(ng, app){
app = angular.module('app', [])
app.factory("service", function(){
var serv = {};
var arr = [];
return {
add : function (title, name, post, tag) {
arr.push({
"title" : title, "name" : name, "post" : post, "tag" : tag
});
},
get : function (firstname) {
return arr[0];
}
}
});
app.controller("createCtrl", ["$scope", "service", function($scope, service)
{
$scope.display = function(){
service.add($scope.title, $scope.name, $scope.post, $scope.tag);
};
}]);
app.controller("newsCtrl", ["$scope", "service", function($scope, service){
$scope.newsPage = "News";
$scope.getData = function(){
$scope.array = service.get();
};
}]);
}(angular));
input {
margin: 5px;
}
<html ng-app="app">
<head>
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>
</head>
<body>
<div ng-controller="createCtrl as main">
<h1>create Ctrl</h1>
<input ng-model="title" placeholder="title" /><br/>
<input ng-model="name" placeholder="name" /><br/>
<input ng-model="post" placeholder="post" /><br/>
<input ng-model="tag" placeholder="tag" /><br/>
<button ng-click="display()"> SAVE DATA </button>
</div>
<br/> <hr/>
<div ng-controller="newsCtrl">
<h2>news Ctrl </h2>
<button ng-click="getData()"> GET DATA </button>
<p> title : {{array.title}} </p>
<p> name : {{array.name}} </p>
<p> post : {{array.post}} </p>
<p> tag : {{array.tag}} </p>
</div>
</body>
</html>
I'm working on one angularjs form which includes location text field. For location text field I'm using google maps to autocomplete. Problem is, I'm unable to store full data database using data-ng-model. Because, only entered text is getting binded and stored in database, not full data. For Example, If I type "Pun" autocomplete populates "Pune, Maharashtra, India", but only "Pun" is storing in database(because I only typed "Pun" in text field. How to capture full data and convert it into json and store it in database? Please help me with this. Thanks in advance.
Here is my code:
JavaScript
<script type="text/javascript">
var app = angular.module('formSubmit', []);
app.controller('FormSubmitController',[ '$scope', '$http', function($scope, $http) {
/* $scope.myDataBlurred = $scope.area; */
$scope.list = [];
$scope.headerText = 'AngularJS Post Form Spring MVC example: Submit below form';
$scope.blurred = function() {
$scope.myDataBlurred = $scope.area;
}
$scope.submit = function() {
var formData = {
"agreement_exp_date" : $scope.agreement_exp_date,
"amenities" : $scope.amenities,
"area": $scope.myDataBlurred,
"bathrooms" : $scope.bathrooms,
"bedrooms" : $scope.bedrooms,
"State": $scope.State,
"city": $scope.city,
"country" : $scope.country,
"current_property_status" :$scope.current_property_status,
"car_spaces" : $scope.car_spaces,
"expired" : $scope.expired,
"furnished" : $scope.furnished,
"floor_or_level" : $scope.floor_or_level,
"house_number" : $scope.house_number,
"notes" : $scope.notes,
"ofname" : $scope.ofname,
"pfname" : $scope.pfname,
"parking_type" : $scope.parking_type,
"pincode" : $scope.pincode,
"prop_avail_date" : $scope.prop_avail_date,
"prpty_owner_email_id" : $scope.prpty_owner_email_id,
"prpty_pm_email_id" : $scope.prpty_pm_email_id,
"prpty_registration_no" : $scope.prpty_registration_no,
"prpty_type" : $scope.prpty_type,
"sqft" : $scope.sqft,
"street_name" : $scope.sqft,
"verified" : $scope.verified,
"prpty_type_sub" : $scope.prpty_type_sub,
"published_on": $scope.published_on,
"profile": $scope.profile
/* "location" : $scope.location,
"phone" : $scope.phone */
};
var response = $http.post('/Owner/addprop', formData);
response.success(function(data, status, headers, config) {
$scope.list.push(data);
});
response.error(function(data, status, headers, config) {
alert( "Exception details: " + JSON.stringify({data: data}));
});
//Empty list data after process
$scope.list = [];
$scope.$setPristine();
};
}]);
</script>
HTML
<div class="col-md-6">
<span> Location<i style="color: red;">*</i>
<div id="locationField">
<input id="autocomplete" name="property_loc"
placeholder="Search for location" onFocus="geolocate()"
type="text" class="form-control" value="${locn}" data-ng-model="area" ng-blur="blurred()" required></input>
</div>
</div>
Go for this code!
It works with the Google Maps API. Start by typing a city name in the input field!
Dont`t look at the warnings and errors. If you add an API key it works without!
var myApp = angular.module('myApp', []);
myApp.directive('googleplace', function() {
return {
require: 'ngModel',
link: function(scope, element, attrs, model) {
var options = {
types: []
};
scope.gPlace = new google.maps.places.Autocomplete(element[0], options);
google.maps.event.addListener(scope.gPlace, 'place_changed', function() {
scope.$apply(function() {
model.$setViewValue(element.val());
});
});
}
};
});
function MyCtrl($scope) {
$scope.gPlace;
}
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>
<script type="text/javascript" src="http://maps.googleapis.com/maps/api/js?libraries=places&sensor=false"></script>
<div ng-app="myApp" ng-controller="MyCtrl">
<div>Your location is: {{chosenPlace}}</div>
<div><input ng-model="chosenPlace" googleplace/></div>
</div>
I am trying to populate a text area with a formatted letter, which comes from a text file. This text file contains objects like {{client.name}} and {{client.address}}, which I would like to replace with the value of the specific client's attribute. Here is the code I have this far,
$scope.loadFlyer = function() {
$http.get("/assets/clientwelcome.txt").then(function(res){
$scope.flyerdescription = res.data;
$scope.flyerdescription = $scope.flyerdescription.replace(/{{client.name}}/g, $scope.client.name);
});
};
Where previously I had called the data from the client's table:
myApp.controller('ClientCtrl', ['$scope', '$http', '$routeParams', function($scope, $http, $routeParams) {
$scope.clients = [];
$http.get('/client').success(function(data, status, headers, config) {
$scope.clients = data;
if (data == "") {
$scope.clients = [];
}
}).error(function(data, status, headers, config) {
console.log("Ops: could not get any data");
});
And this is the field that I am trying to populate:
<div class="form-group">
<label class="control-label" for="flyer-description">Description</label>
<textarea style="height:400px" class="form-control" id="flyer-description" ng-model="flyerdescription"></textarea>
</div>
Unfortunately, no replacing is done. I've tried to format the replace as I have seen in the javascript documents, but to no avail.
Editted* per discussion below
You have a list of clients that looks like [{name: 'Hank Aaron'}, {name: 'Sandy Koufax'}, {name: 'Bo Jackson'}], and a template string, that contains a value: '{{client.name}}', that you want to replace with a name from your clients list.
myApp.controller('ClientCtrl', ['$scope', '$http', '$routeParams', function($scope, $http, $routeParams) {
$scope.clients = [];
$http.get('/client').success(function(data, status, headers, config) {
$scope.clients = data;
if (data == "") {
$scope.clients = [];
}
}).error(function(data, status, headers, config) {
console.log("Ops: could not get any data");
});
$scope.loadFlyer = function() {
$http.get("/assets/clientwelcome.txt").then(function(res){
$scope.flyerdescription = res.data;
$scope.descriptions = [];
for(var i=0; i<$scope.clients.length; i++){
$scope.descriptions[i].push($scope.flyerdescription.replace(/{{client.name}}/g,$scope.clients[i].name));
}
});
};
}]);
and in your HTML
<div class="form-group">
<div ng-repeat="description in descriptions">
<label class="control-label" for="flyer-description">Description</label>
<textarea style="height:400px" class="form-control" id="flyer-description" ng-model="description"></textarea>
</div>
</div>
<html>
<head>
<script src="http://ajax.googleapis.com/ajax/libs/angularjs/1.4.8/angular.min.js"></script>
</head>
<body>
<div ng-app="demoApp" ng-controller="validationCtrl" class="form-group">
<label class="control-label" for="flyer-description">Description</label>
<textarea style="height:100px" class="form-control" id="flyer-description" ng-model="stringname
"></textarea>
</div>
<script>
//This is controller
var app = angular.module('demoApp', []);
app.controller('validationCtrl', function($scope) {
$scope.stringname = 'angular123456 test demo';
$scope.stringname = $scope.stringname.replace('test', "");
});
</script>
</body>
</html>
I used Spring framework as a back-end and angular as a front end. When I try to insert data from the angualrJs value is inserted into database but display error code. please suggest me what is the wrong in this code.
var app = angular.module("categoryApp", []);
app.controller('submitCategory', [ '$scope', '$http',
function($scope, $http) {
$scope.submitClick = function() {
var dataObj = {
name : $scope.name
};
var result = $http.post("/tutorials/category", dataObj);
result.success(function(data, status, headers, config) {
alert("success");
$scope.message = data;
});
result.error(function(data, status, headers, config) {
alert("failure message: " + JSON.stringify({
data : data
}));
});
$scope.name = '';
}
}
]);
And my html is
<body ng-app="categoryApp">
<section class="panel" ng-controller="submitCategory">
<header class="panel-heading"> Basic Forms </header>
<div class="panel-body">
<form role="form" method="post" ng-submit="submitClick()">
<div class="form-group">
<label for="category">Category</label> <input type="text"
class="form-control" id="exampleInputEmail1" name="name"
placeholder="Category" ng-model="name">
</div>
<button type="submit" class="btn btn-primary">Submit</button>
</form>
</div>
</section>
</body>
And my controller method is
#RequestMapping(value = "/category", method = RequestMethod.POST)
public ResponseEntity<String> postCategory(#RequestBody Category category,
Model model) {
categoryService.save(category);
return new ResponseEntity<String>("success", HttpStatus.OK);
}
The issue is caused by ResponseEntity<String> .Your code java should be like this:
#RequestMapping(value = "/category", method = RequestMethod.POST)
public ResponseEntity<String> postCategory(#RequestBody Category category,
Model model) {
categoryService.save(category);
return new ResponseEntity<String>("success", HttpStatus.OK); }
So I have a form inside an ng-dialog plugin for angular js. The contents of the ng-dialog is loaded from external html file. The problem is that when I try to save the data it is undefined. I suspect that I am missing updating the ng-model that I use, but it is not clear how to do it. I have looked to some similar examples, but it still does not work.I want to collect the data when the button inside the form is pressed, not when the dialog is closed, but when closed will do as well. Here is my code:
angular.app.js
myApp.controller('RequestController', function ($scope, $http, $location, $window, subtitleRequestService, $sce, subtitlesApiServiceUrl, helperService, ngDialog) {
$scope.string_identifier = helperService.getParameterByName("v");
$scope.availableSubtitles = null;
$scope.request = {
status: "pending",
status_reason: "",
status_reason_f: ""
};
var getAvailableSubtitles = function()
{
subtitleRequestService.getAvailableSubtitlesForRequest().then(
function (res) {
var subs = res.data.message;
$scope.availableSubtitles = subs;
},
function () {
alert('Error');
}
);
};
$scope.saveStatus = function()
{
var sts = ($scope.request.status_option === "accepted" ? $scope.request.status_reason : $scope.request.status_reason_f);
$http.post(subtitlesApiServiceUrl + "changeRequestStatus/request_id/" + $scope.string_identifier + "/status/" + $scope.request.status + "/status_reason/" + sts)
.success(function (data, status, headers, config) {
alert(data.message);
}).error(function (data, status, headers, config) {
alert(data);
});
};
$scope.changeStatus = function()
{
getAvailableSubtitles();
var dialogInstance = ngDialog.open({
//appendTo: window.parent.document.getElementsByTagName('body'),
template: "/templates/change-request-status.html",
scope: $scope,
controller: 'RequestController',
className: 'ngdialog-theme-default'
});
};
});
externalTeamplate.html
<div class="ngdialog-message" ng-controller="RequestController">
<h3>Schimbă status</h3>
<div class="form">
<form class="form" name="$scope.request">
<div class="row">
<label for="status_options">Status</label>
<select name="status_options" id="status_options" ng-model="request.status_option">
<option value="pending" selected="selected">În procesare</option>
<option value="accepted">accepted</option>
<option value="rejected">rejected</option>
<option value="deleted">deleted</option>
<option value="in_translation">in_translation</select>
</select>
</div>
<div class="row" ng-show="request.status_option !== 'accepted'">
<label for="status_reason">Reason:</label>
<input type="text" id="status_reason" size="35" maxlength="144" ng-model="request.status_reason" />
</div>
<div class="row" ng-show="request.status_option=='accepted'">
<label for="status_reason_f">Please select:</label>
<select id="status_reason_f" ng-repeat="(key, value) in availableSubtitles" ng-model="request.status_reason_f">
<option value="{{key}}">{{value}}</option>
</select>
</div>
</form>
</div>
</div>
<div class="ngdialog-buttons">
<button type="button" class="ngdialog-button ngdialog-button-primary" ng-click="saveStatus()">Salvează</button>
</div>
What am I missing? Thanks!