I have a form which makes uses of google map's Places API.
My form has following fields:
1) text box to enter name.
2) text box to fetch google address.
3) text box which saves latitude from google address.
4) text box which saves longitude from google address.
And I'm trying to pass all these values to a backend service but the values set by places api is not getting passed as a parameter to the service:
Here's my HTML:
<div ng-app="myApp" ng-controller="myMap">
<form name="addForm" ng-submit="vm.addForm()" novalidate>
<div class="form-group">
<input type="text" name="name" id="name" ng-model="vm.name" placeholder="Name" />
<h2>Address</h2>
<input type="text" id="source_point" name="source_point" ng-model="vm.source_point" placeholder="Enter address here">
<input type="text" id="src_lat" name="src_lat" ng-model="vm.src_lat" placeholder="latitude">
<input type="text" id="src_long" name="src_long" ng-model="vm.src_long" placeholder="longitude">
</div>
<button type="submit">Add Data</button>
</form>
</div>
<div id="source_map"></div>
and my Controller looks like this:
angular.module('myApp', [])
.factory('myService', function($http) {})
.controller('myMap', function(myService, $http, $scope) {
var vm = this;
var map;
var marker;
var latLngC;
var places1 = new google.maps.places.Autocomplete(document.getElementById('source_point'));
google.maps.event.addListener(places1, 'place_changed', function() {
var place1 = places1.getPlace();
var src_addr = place1.formatted_address;
var src_lat = place1.geometry.location.lat();
var src_long = place1.geometry.location.lng();
var mesg1 = "Address: " + src_addr;
mesg1 += "\nLatitude: " + src_lat;
mesg1 += "\nLongitude: " + src_long;
document.getElementById('src_lat').value = src_lat;
document.getElementById('src_long').value = src_long;
});
$scope.post = {};
$scope.post.addForm = [];
$scope.vm = {};
$scope.index = '';
var baseUrl = 'api/';
// function to submit the form after all validation has occurred
vm.addForm = function() {
var dataPost = {
eventName: $scope.vm.name,
eventLocation: $scope.vm.source_point,
eventLocLat: $scope.vm.src_lat,
eventLocLong: $scope.vm.src_long
};
return $http({
method: 'post',
url: baseUrl + 'addFormData',
data: dataPost,
headers: {
'Content-Type': 'application/x-www-form-urlencoded'
}
});
}
});
HERE's a FIDDLE
What could be the possible reason?
Setter to input for longitude and latitude is wrong:
$scope.$apply(function() {
$scope.vm.src_lat = src_lat;
$scope.vm.src_long = src_long;
});
instead of
document.getElementById('src_lat').value = src_lat;
document.getElementById('src_long').value = src_long;
Put values into scope and angular will makes the rest :)
Related
I have a web page that asks user to enter number of networks. Based on number provided by user, it creates corresponding amount of text input fields. User than enters network addresses in those newly created boxes and when user clicks validate, it pings each networks.
Now, I managed to get the dynamically creation on input fields done but now I am having issue accessing their values. Please see below code and jsfiddle:
HTML:
<div ng-app>
<div ng-controller="Controller">
<div class="form-group" id = "numNetDiv" style="display:block">
<div class="col-sm-3">
<label for="numNetworks">Number of Networks</label>
<input id="numNetworks" ng-model="numNetworks"
ng-change="addNetworkFields()" type="text"
class="form-control" required />
<div class="col-sm-3" id="container" style="margin-left: 50px">
</div>
</div>
</div>
<div class="form-group" id = "checkNetsDiv" style="display:block">
<div>
<button id="checkNets" type="button" class="btn btn-nets"
style="margin-left: 100px"
ng-click="checkNets()">
Validate
</button>
</div>
</div>
<p id="demo"></p>
</div>
</div>
angularjs:
// Add input boxes based on # of networks
function Controller($scope){
$scope.count=0;
$scope.addNetworkFields = function() {
var number = document.getElementById("numNetworks").value;
console.log(number);
var container = document.getElementById("container");
while (container.hasChildNodes()) {
container.removeChild(container.lastChild);
}
for (i=0;i<number;i++){
container.appendChild(document.createTextNode("Network" + (i+1) + ": "));
var input = document.createElement("input");
input.type = "text";
container.appendChild(input);
container.appendChild(document.createElement("br"));
}
}
// Run ping on each subnet
$scope.checkNets = function() {
console.log('Click!')
var number = document.getElementById("numNetworks").value;
for (i=0;i<number;i++){
//Access each networks and run ping on each one after another
// Call below for each network to perform ping
var ping = $.param({network: $scope.network[i]}); // [i] to access each network? Just an idea
$http({
url: 'https://' + location.hostname + '/ping_network',
method: "POST",
data: ping
})
.then(function(response) {
$scope.pingResult = response.data;
})
}
}
}
https://jsfiddle.net/Lwy378ce/137/
I know POST works and the only issue I am having is access each networks one by one and calling that POST on it. For testing, we can get ride of the whole POST code and replace it with something like console.log(network[i]) and see if console can list all networks.
Thanks
Damon
It would be much simpler if you just used a form and the angular js models. You could create your field with ng-repeat, make the ng-model of these input fields the network address and then use those address for the ping. Addresses that would be easily updated when the form is submitted. Also by using ng-show you can hide that validate button until it's useful.
It's also a lot less code.
angular.module('myApp', [])
.controller('myAppCtrl', function($scope){
$scope.number = 0;
$scope.addNetworkFields = function(value) {
$scope.networks = [];
for(var i = 1; i <= parseInt(value); i++){
var network = {number : i, address: ""}
$scope.networks.push(network)
}
}
$scope.submit = function() {
for(var i = 0; i < $scope.networks.length; i++){
console.log($scope.networks[i].address)
}
}
});
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>
<body ng-app="myApp" ng-controller="myAppCtrl as ctrl" ng-cloak layout="column" layout-fill>
<form ng-submit="submit()" class="form-group" id = "numNetDiv" style="display:block">
<div class="col-sm-3">
<label for="numNetworks">Number of Networks</label>
<input id="numNetworks" ng-model="number"
ng-change="addNetworkFields(number)" type="number"
class="form-control" required />
<div class="col-sm-3" id="container" style="margin-left: 50px">
<div ng-repeat="network in networks">
<label>Networks {{network.number}}
<input ng-model="network.address"
type="text" class="form-control" /></label>
</div>
<input ng-show="number > 0" type="submit" value="validate"/>
</div>
</div>
</form>
</body>
Here you go: set id to each input and get it by id later.
// Add input boxes based on # of networks
function Controller($scope) {
$scope.count = 0;
$scope.addNetworkFields = function() {
var number = document.getElementById("numNetworks").value;
console.log(number);
var container = document.getElementById("container");
while (container.hasChildNodes()) {
container.removeChild(container.lastChild);
}
for (i = 0; i < number; i++) {
container.appendChild(document.createTextNode("Network" + (i + 1) + ": "));
var input = document.createElement("input");
input.type = "text";
input.id = "network" + (i + 1);
container.appendChild(input);
container.appendChild(document.createElement("br"));
}
}
// Run ping on each subnet
$scope.checkNets = function() {
console.log('Click!')
var number = document.getElementById("numNetworks").value;
for (i = 0; i < number; i++) {
//Access each networks and run ping on each one after another
var network = document.getElementById("network" + (i + 1)).value
// Call below for each network to perform ping
var ping = $.param({
network: $scope.network
});
$http({
url: 'https://' + location.hostname + '/ping_network',
method: "POST",
data: ping
})
.then(function(response) {
$scope.pingResult = response.data;
})
}
}
}
I have two html, first sends value to another. I want in second html receive data in javascript. On first html page user would be able to insert localhost:8888 address, address should be send to java script in another html...for now i have default address in java script .. please help.
first html
<form action="second.html" method="GET" >
<input type="text" name="" />
<input type="submit" value="Submit" />
</form>
</body>
</html>
second html
<script>
$(document).ready(function () {
var ws = new WebSocket("ws://localhost:8888/ws");
ws.onopen = function(evt) {
var conn_status = document.getElementById('conn_text');
conn_status.innerHTML = "Status: Connected!"
};
...
got more code
<script>
...
You can get submitted data from URL, because your from has submit method GET:
first html:
<form action="second.html" method="GET" >
<!-- In this way we can get submitted data from get param "host" -->
<input type="text" name="host" />
<input type="submit" value="Submit" />
</form>
second html:
<script>
$(document).ready(function () {
// function to get params from url
function getQueryParams(query) {
query = query || window.location.search;
if (query.length === 0) {
return {};
}
var params = {};
var paramsArr = query.split('&');
for (var i = 0; i < paramsArr.length; i++) {
var p = paramsArr[i].split("=");
params[p[0]] = p[1] || '';
}
return params;
}
// try to get param "host" from url (which submitted from first html)
var queryParams = getQueryParams();
var host = queryParams.host || 'localhost:8888';
var ws = new WebSocket('ws://' + host + '/ws');
ws.onopen = function (evt) {
var conn_status = document.getElementById('conn_text');
conn_status.innerHTML = "Status: Connected!"
};
// more code
}
</script>
In Angular (1.5) I have a form with two input fields:
ID
URL
The rules:
If the ID field is empty then the URL field should be empty
If the URL field is manually set then it should not change automatically
Otherwise the URL field should be "http://myurl/"+ID+".txt"
How do I achieve this?
<input type="text" name="url"
ng-model="url"
ng-model-options="{ getterSetter: true }" />
...
function defaulUrl() {
if $scope.ID {
return 'http://myurl/'+$scope.ID+'.txt';
}
return ''
}
var _url = defaultURl();
$scope.url = {
url: function(url) {
return arguments.length ? (_url= url) : defaulUrl();
}
}
};
Use $watch on ID Field. If the ID field is changed, the watch function will be called.
$scope.$watch('$scope.ID', function() {
$scope.url = 'http://myurl/' + $scope.ID + '.txt';
}, true);
Here is a fiddle I made that meets your requirments:fiddle
The code
//HTML
<div ng-app="myApp" ng-controller="MyController">
ID <input type="text" ng-model="data.id" ng-change="onIDChange()"/>
URL <input type="text" ng-model="data.url" ng-change="onManualUrlChange()"/>
</div>
//JS
angular.module('myApp',[])
.controller('MyController', ['$scope', function($scope){
$scope.data = {
id:'',
url:''
}
$scope.manualUrl = false;
$scope.onIDChange = function(){
if(!$scope.manualUrl){
if($scope.data.id === ''){
$scope.data.url = '';
} else {
$scope.data.url = "http://myurl/" + $scope.data.id + ".txt";
}
}
}
$scope.onManualUrlChange = function(){
$scope.manualUrl = true
};
}]);
I've recently started using AngularJS, and even though I am able to send data through $http when the webpage loads, I'm unable to do it when a button is pressed. My code:
<div ng-app="myApp" ng-controller="myCtrl">
Username: <input type="text" id="u" ng-model="username"><br>
Password: <input type="text" id="p" ng-model="password"><br>
Email: <input type="text" id="e" ng-model="email"><br>
First Name: <input type="text" id="fn" ng-model="firstName"><br>
Last Name: <input type="text" id="ln" ng-model="lastName"><br>
<br>
<button onclick="sendData()">Click me</button>
<br>
{{status}}
</div>
<script>
var app = angular.module('myApp', []);
var arr = new Array();
function sendData() {
arr[0] = document.getElementById("u").value;
arr[1] = document.getElementById("p").value;
arr[2] = document.getElementById("e").value;
arr[3] = document.getElementById("fn").value;
arr[4] = document.getElementById("ln").value;
app.controller('myCtrl', function($scope, $http) {
$http.post("../signup.php", {'data' : arr})
.success(function(response) {
$scope.status = response.status;
$scope.description = response.description;
$scope.content = response.content;
});
});
}
</script>
With that code, the function in app.controller doesn't execute, but if I put it outside of the sendData() function, it does execute, but right after loading the page.
Can anyone help me getting it to work when the button is pressed?
SInce you want to use angular and you use ng-model in your view you should use ng-click on your button:
<button ng-click="sendData()">Click me</button>
Even better you can use ng-submit on your form and use a submit button.
In your controller you will have something like this:
$scope.username = '';
$scope.email = '';
// better have an user object here so you will not have n variables ...
$scope.sendData = function() {
var arr = [];
arr[0] = $scope.username;
arr[1] = $scope.email;
//........
$http.post("../signup.php", {data : arr})
.success(function(response) {
$scope.status = response.status;
$scope.description = response.description;
$scope.content = response.content;
});
}
You need to define the function on the scope of your controller
HTML
<button ng-click="sendData()">Click me</button>
JS
app.controller('myCtrl', function($scope, $http) {
$scope.sendData = function(
$http.post("../signup.php", {'data' : arr})
.success(function(response) {
$scope.status = response.status;
$scope.description = response.description;
$scope.content = response.content;
});
}
});
Why does this code work (As far as it pulls back an empty "CustomerObject" viewable in Chrome console
var CustomerObject = Parse.Object.extend("CustomerObject");
var retrieve = new Parse.Query(CustomerObject);
retrieve.equalTo("customernumber", $('#searchnumber').val());
retrieve.first({
success: function(retrieveResults)
{
}
});
var cname = retrieve.get("customername");
var cnumber = retrieve.get("customernumber");
But this code inside a function does not return any "CustomerObject" when the user clicks the search button?
HTML
<input type="text" name="searchnumber" id="searchnumber" value="" placeholder="Customer Number"/>
<button type="submit" onclick = "search" >Find</button>
JS
function search() {
var CustomerObject = Parse.Object.extend("CustomerObject");
var retrieve = new Parse.Query(CustomerObject);
retrieve.equalTo("customernumber", $('#searchnumber').val());
retrieve.first({
success: function(retrieveResults)
{
}
});
var cname = retrieve.get("customername");
var cnumber = retrieve.get("customernumber");
};
missing bracket <button type="submit" onclick = "search() " >Find</button>