I am building an App using Ionic / Angular JS. In a specific tab, the app has the ability to fill some form fields automatically like Street Name, Street Number, etc. My problem is that, in some situations the Street Number for example is not available and data[0].address_components[0].long_name fills the Street Name instead.
Here is the code that I use:
.controller('PetitionsCtrl', function($scope, $cordovaGeolocation, $cordovaCamera, $log, $ionicLoading, $http, $timeout, $compile, Upload) {
$scope.getLocation = function() {
$ionicLoading.show({
templateUrl: 'loading.html',
hideOnStateChange: true
});
var posOptions = {timeout: 15000, enableHighAccuracy: true};
$cordovaGeolocation
.getCurrentPosition(posOptions)
.then(function (position) {
$scope.lat = position.coords.latitude;
$scope.lng = position.coords.longitude;
$scope.pLat = {value: $scope.lat};
$scope.pLng = {value: $scope.lng};
var geocoder = new google.maps.Geocoder();
var latlng = new google.maps.LatLng($scope.lat, $scope.lng);
var request = {
latLng: latlng
};
geocoder.geocode(request, function(data, status) {
if (status == google.maps.GeocoderStatus.OK) {
if (data[0] != null) {
$scope.$apply(function () {
$scope.pStreet = {value: data[0].address_components[1].long_name};
$scope.pNumber = {value: data[0].address_components[0].long_name};
$scope.pCity = {value: data[0].address_components[2].long_name};
$scope.pAddress = {value: data[0].formatted_address};
setTimeout(function () {
$ionicLoading.hide();
}, 500);
});
} else {
$log.log("Adresa indisponibila");
setTimeout(function () {
$ionicLoading.hide();
}, 500);
}
}
})
});
};
})
Here is an example response from Google:
{
"results" : [
{
"address_components" : [
{
"long_name" : "1600",
"short_name" : "1600",
"types" : [ "street_number" ]
},
{
"long_name" : "Amphitheatre Pkwy",
"short_name" : "Amphitheatre Pkwy",
"types" : [ "route" ]
},
{
"long_name" : "Mountain View",
"short_name" : "Mountain View",
"types" : [ "locality", "political" ]
},
{
"long_name" : "Santa Clara County",
"short_name" : "Santa Clara County",
"types" : [ "administrative_area_level_2", "political" ]
},
{
"long_name" : "California",
"short_name" : "CA",
"types" : [ "administrative_area_level_1", "political" ]
},
{
"long_name" : "United States",
"short_name" : "US",
"types" : [ "country", "political" ]
},
{
"long_name" : "94043",
"short_name" : "94043",
"types" : [ "postal_code" ]
}
],
"formatted_address" : "1600 Amphitheatre Parkway, Mountain View, CA 94043, USA",
"geometry" : {
"location" : {
"lat" : 37.4224764,
"lng" : -122.0842499
},
"location_type" : "ROOFTOP",
"viewport" : {
"northeast" : {
"lat" : 37.4238253802915,
"lng" : -122.0829009197085
},
"southwest" : {
"lat" : 37.4211274197085,
"lng" : -122.0855988802915
}
}
},
"place_id" : "ChIJ2eUgeAK6j4ARbn5u_wAGqWA",
"types" : [ "street_address" ]
}
],
"status" : "OK"
}
How can I alter my code so it checks the "types" value before reading a value and leaves it empty if not available. To be more speicifc, instead of using data[0].address_components[0].long_name to get the street number, I would like to get if "types" vale is "street_number".
What I have understood is that if the types value is equal to street_number you want to get the value otherwise you want to put empty as a value ''
geocoder.geocode(request, function(data, status) {
if (status == google.maps.GeocoderStatus.OK) {
if (data[0] != null) {
$scope.$apply(function () {
$scope.pStreet = {value: data[0].address_components[1].long_name};
$scope.pNumber = {value: data[0].address_components[0].types[0] === 'street_number' ? data[0].address_components[0].long_name : ''};
$scope.pCity = {value: data[0].address_components[2].long_name};
$scope.pAddress = {value: data[0].formatted_address};
setTimeout(function () {
$ionicLoading.hide();
}, 500);
});
} else {
$log.log("Adresa indisponibila");
setTimeout(function () {
$ionicLoading.hide();
}, 500);
}
}
})
You have to loop over result set to find a match like:
Angular.forEach(data[0].address_components, function(val, index){
if (val.type[0]=='street_number') {
$scope.pNumber = {value: val.long_name};
}
});
You can use this code to find any other value like city or country etc.
Ryad.iv answer is just checking the first string in the array. For this to work properly you have to check all the elements of the array.
geocoder.geocode(request, function(data, status) {
if (status == google.maps.GeocoderStatus.OK) {
if (data[0] != null) {
$scope.$apply(function () {
$scope.pStreet = {value: data[0].address_components[1].long_name};
$scope.pNumber = {value: data[0].address_components[0].types.indexOf('street_number') !== -1 ? data[0].address_components[0].long_name : ''};
$scope.pCity = {value: data[0].address_components[2].long_name};
$scope.pAddress = {value: data[0].formatted_address};
setTimeout(function () {
$ionicLoading.hide();
}, 500);
});
} else {
$log.log("Adresa indisponibila");
setTimeout(function () {
$ionicLoading.hide();
}, 500);
}
}
})
That's the good way of checking this. With the other answer, if street_name is the second position of the array you will not be inserting it correctly.
Hope it helps
Related
This is my first stack overflow question, and I'm excited to hear your thoughts.
> db.travelers.find().pretty()
{
"_id" : ObjectId("615e3ddece93c870aca4e465"),
"assembly" : [
{
"_id" : ObjectId("615e3ddece93c870aca4e466"),
"SN" : 24,
"Model" : "J240",
"Job" : 1234,
"Revision" : "A",
"Version" : 1
}
],
"assyHistory" : [ ],
"subAssemblies" : [
{
"_id" : ObjectId("615e3deace93c870aca4e467"),
"SN" : 19,
"Model" : "P500"
}
I am trying to delete the nested data in "subAssemblies" by its id. My current route:
router.delete("/subassembly/:id", deleteOneSubassembly);
my current controller:
deleteOneSubassembly: async (req, res) => {
try {
const removeOne = await Traveler.deleteOne({
_id: req.params.id
});
console.log(removeOne);
res.json(removeOne);
} catch (err) {
res.send({ error: err });
}
}
And all I keep getting back is:
"n": 0,
"nModified": 0,
"ok": 1
Wondering where I might be going wrong?
use update and $pull the item
const removeOne = await Traveler.updateOne(
{
"subAssemblies._id": req.params.id
},
{
"$pull": { subAssemblies: { _id: req.params.id }
}
});
aggregate
db.collection.update({
"subAssemblies._id": ObjectId("615e3deace93c870aca4e467")
},
{
$pull: {
subAssemblies: {
_id: ObjectId("615e3deace93c870aca4e467")
}
}
})
mongoplayground
var arr = Array [ Object, Object ]
into arr {
"name" : "xyz",
"age" : "22",
"sports" : Array[
{
id:1,
name : "xyz",
},
{
id:2,
name : "yyy",
},
]
}
var obj = Object { name: "JXZ", id :1};
var response = _.filter(arr, function(user) {
return user.sports.id === obj.id;
});
filter the record that match with obj's id from arr's sports.id return array object.
I'm suppose to put loop but i guess that not right solution if please
Please try this below code.
<script>
var app = angular.module('app',[]);
app.controller('ctrl',function($scope){
$scope.arr = Array [ Object, Object ];
$scope.arr = {
"name" : "xyz",
"age" : "22",
"sports" : [
{
id:1,
name : "xyz",
},
{
id:2,
name : "yyy",
}
]
}
var obj = { name: "JXZ", id :1};
var filteredSports = _.filter($scope.arr.sports, function (sport) {
return sport.id == obj.id;
})
$scope.arr.sports = filteredSports;
console.log($scope.arr);
})
</script>
I'm fetching a Json with a factory "chapters", so I get the value of the property "json_file" which is another json file that I need to fetch dynamically with the factory "contents". I just need to pass the parameter "json_file" to the second factory, but I get an undefined value.
Maybe I need a service?
This is the first json file:
structure.js
[
{
"title": "Introduction",
"pages": [
{
"title": "Buongiorno",
"type" : "standard",
"json_file" : "cover_1"
},
{
"title": "Introduction",
"type" : "standard",
"json_file" : "cover_1"
}
]
},
{
"title": "Storytelling",
"pages": [
{
"title": "Italian Design & Swiss Watchmaking Expertise",
"type" : "standard",
"json_file" : "cover_1"
},
{
"title": "Interaction",
"type" : "standard",
"json_file" : "cover_1"
}
]
}
]
This is the controller.js
var bControllers = angular.module('bControllers',[]);
bControllers.controller('structureCtrl', function ($scope, $routeParams,chapters,contents){
$scope.indexChapter = 0;
$scope.indexPage = 0;
chapters.list(function(chapters) {
$scope.chapters = chapters;
$scope.pages = [];
$scope.json_file = [];
angular.forEach($scope.chapters, function(chapters,index){
angular.forEach(chapters.pages, function(page,index2){
$scope.pages.push(page);
$scope.json_file.push(page.json_file);
})
});
$scope.currentJson = $scope.chapters[$scope.indexChapter].pages[$scope.indexPage].json_file;
console.log('json-file:'+$scope.currentJson);
return $scope.currentJson;
});
contents.find($scope.currentJson, function(content) {
$scope.content = content;
});
});
And this is the factory.js
var bFactory = angular.module('bFactory',[]);
bFactory.factory('chapters', function($http){
return {
list: function (callback){
$http({
method: 'GET',
url: 'json/structure.json',
cache: true
}).success(callback);
}
}
});
bFactory.factory('contents', function($http){
return{
find:function(json_file, callback){
$http({
method: 'GET',
url: 'json/'+json_file+'.json',
cache: true
}).success(callback);
}
}
})
How can I get the output in tree structure by matching the parent? I can only use a single ng-repeat to display this.
My expected output
firstname :-dsfsdf
lastname :- fdsfsdfs
account:
role:-dsfsdf
status:-dsfdfsfds
js
var app = angular.module("test",[]);
app.controller("MainCtrl",function($scope){
$scope.inputs = [
{
"firstname" : "Test"
},{
"lastname" : "Test1"
},{
"Account" : [
{"role" : "Test3"},
{"status" : "Test4"},
]
},
{
"Account1" : [
{"role" : "Test3"},
{"status" : "Test4"},
]
},
{
"Account2" : [
{"role" : {
'dim3': {
'dim4':{
'dim5':'cccc'
}
}
}
},
{"status" : "Test4"},
{"status" : "Test4"},
]
},
{
"ending" : "yes"
}
];
/*$scope.person = [];*/
$scope.myPersonObj = [];
$scope.checkIndex1 = function(arg, myPersonObj)
{
if (angular.isArray(arg) || angular.isObject(arg)) {
angular.forEach(arg, function (value, key) {
console.log(value + "started");
if(angular.isObject(value) || angular.isArray(value))
{
$scope.checkIndex1(value, myPersonObj);
}
else
{
console.log( value + "pushing--test");
myPersonObj.push(arg);
}
});
}
else
{
console.log( value + "pushing1");
myPersonObj.push(arg);
}
}
$scope.checkIndex1($scope.inputs, $scope.myPersonObj);
console.log("myPersonObj :"+ JSON.stringify($scope.myPersonObj));
console.log($scope.inputs[2] + "del");
}):
I need to make a filter that searches the following array of objects and filters out those objects whose ID value is equal to a Message value in any of those objects in the array. Also the filter should return only objects with level equal to 1. I've already managed to filter the level property, but I can't seem to figure out how to do the rest.
Let's consider an example: ID: 001 contains in its Message 006, so I want to filter out all objects, whose ID is 006.
$scope.myData = [
{
"ID" : "001",
"Message" : "006",
"level":"1"
},
{
"ID" : "002",
"Message" : "test test test test1",
"level":"1"
},
{
"ID" : "003",
"Message" : "test test test test",
"level":"1"
},
{
"ID" : "004",
"Message" : "test test test test",
"level":"1"
},
{
"ID" : "005",
"Message" : " My Test",
"level":"1"
},
{
"ID" : "006",
"Message" : "",
"level":"1"
},
{
"ID" : "007",
"Message" : "next level",
"level":"2"
}
];
})
And filter:
app.filter('filterData3', function () {
return function (data) {
var dataToBePushed = [];
data.forEach(function (resultData) {
if (resultData.level == 1)
dataToBePushed.push(resultData);
});
return dataToBePushed;
}
});
Assuming that what you want is to NOT include in your filtered array the elements which ID is contained in another element's Message, you could write a filter like the following:
.filter('filterData3', function () {
return function (data) {
var dataToBePushed = [];
var messages =[];
data.forEach(function (resultData) {
if (resultData.level == 1 && (messages.indexOf(resultData.ID) == -1)) {
messages.push(resultData.Message);
dataToBePushed.push(resultData);
}
});
return dataToBePushed;
}})
Hope this works for you