How to change values retrieved from json url in Angular - angularjs

I have a service that retrieves a JSON from an url, I use ng-repeat to show values in a list.
My JSON looks like this:
[
{"iconuser":"livingroom1","class":"w5","status":"0"},
{"iconuser":"meetingroom1","class":"w4","status":"1"}
]
How do I replace some values of that object.
example:
status = 0 should be status = OFF
status = 1 should be status = ON

In native angular:
$scope.item = [{"iconuser":"livingroom1","class":"w5","status":"0"},
{"iconuser":"meetingroom1","class":"w4","status":"1"}];
angular.forEach($scope.item,, function(obj) {
if(obj.status === 0)
obj.status = "OFF";
else
obj.status = "ON";
return obj;
});

You can use Array.map to format your response:
var formattedData = responseData.map(function(obj) {
if (obj.status === 0) {
obj.status = "OFF";
} //etc
return obj;
});

Related

trying to convetr json array to multiple json objects in nodejs

trying to convetr json array to multiple json objects in nodejs looking for help here is my code have tried loops to achieve that but failed just want to send the data as multiple objects not array
router.get('/frontpage-mobile', function (req, res, next) {
qryFilter = { "Product_Group": 'SIMPLE' };
// if we have a cart, pass it - otherwise, pass an empty object
var successMsg = req.flash('success')[0];
var errorMsg = req.flash('error')[0];
Product.find(qryFilter, function (err, product) {
// console.log("Product: " + JSON.stringify(product));
var pro=JSON.stringify(product)
if (err || product === 'undefined' || product == null) {
// replace with err handling
var errorMsg = req.flash('error', 'unable to find product');
res.send(errorMsg);
}
if (!product) {
req.flash('error', 'Product is not found.');
res.send('error', 'Product is not found.');
}
for(i=0;i<pro.length;i++)
res.send(pro[i]);
});
});
// Dummy Mongodb Result Array
var db_result = [{_id:1,name:"Cake_1"},{_id:2,name:"Cake_2"},{_id:3,name:"Cake_3"}]
// define data variable
var data = { total : 0, dataObj : {} } // default total = 0, = {}
var dataObj = {}
// convert array to obj
// { key1 : obj1, key2 : obj2, key3 : obj3, ... }
for(var i=0; i < db_result.length;i++){
let key = "key"+i;
dataObj[key] = db_result[i];
}
// assign data to variable
data.total = db_result.length;
data.dataObj = dataObj
// rend back to client
res.send(data);
// Result
{
"total":3,
"dataObj":{
"key0":{"_id":1,"name":"Cake_1"},
"key1":{"_id":2,"name":"Cake_2"},
"key2":{"_id":3,"name":"Cake_3"}
}
}

How to fetch child node inside nested firebase DB

Hi,I was to fetch only the nodes where category = "Tribal" and return it as firebase array object.Thanks in advance.
Angular Service CODE:
this.getSpecialTourPackage = function(){
var dbRef = firebase.database().ref('states').child('itineraries');
return $firebaseArray(dbRef);
};
Angular Controller CODE:
if(_category != undefined && _category == 'Tribal'){
var loadedResult = [];
var resultArray = indiaTourService.getSpecialTourPackage();
resultArray.$loaded().then(function(data){
data.forEach(item =>{
loadedResult.push(item);
$scope.itineraries = _.where(loadedResult,{ category : "Tribal"});
});
});
}

Return promise from Angularjs webapi

Using Angularjs here:
I have a form where user fills up some data and clicks save button to save data :
$scope.save = function (isValid) {
if (isValid) {
if (!$scope.checkBoxChecked) {
$scope.getExistingName($scope.uName);
}
var name = $scope.uName != '' ? $scope.uName? : 'testuser';
//Call save api
}
else {
return false;
}
};
In the save method I am checking for uname, which gets it value by calling another api as below:
$scope.getExistingName = function (uName) {
myService.getDataFromApi(uName).then(function (data) {
var existingSetName = '';
if(data.length >0)
{
$scope.uName = data[i].uName;
}
});
}
The issue is $scope.uName in my Save button is always ''. I tried to debug and found out that the result from the $scope.getExistingName method
being is promise is deffered and returned after the orignal call. Because of which my $scope.uName is empty.
What am I missing here?
--Updated---
Save method:
var name = $scope.getExistingName($scope.uName);
Updated getExistingName
$scope.getExistingName = function (uName) {
return myService.getDataFromApi(uName).then(function (data) {
var existingSetName = '';
if(data.length >0)
{
return data[i].uName;
}
});
}
--This works--
if (!$scope.checkBoxChecked) {
$scope.getExistingName($scope.uName).then(function(data)
{
var name = $scope.uName != '' ? $scope.uName? : 'testuser';
//Call save api
});
}
else
{
var name = $scope.uName != '' ? $scope.uName? : 'testuser';
//Call save api
}

How to check string in json array

console.log($scope.filteredOffers);hi to all want to check string in json like that string coming form params now want to check in whole json and display only data which is related to that . Kindly check my code .. in other words want to display data according to the params which is coming form url (which is coming ).
.controller('mixCtrl', function($scope,$http,$stateParams) {
$http.get("http://tools.vcommission.com/api/coupons.php?apikey=e159f64e3dd49fddc3bb21dcda70f10c6670ea91aac30c7cb1d4ed37b20c45b8").then(function (response) {
$scope.myData = response.data;
$scope.offerName = ''; //set initially
$scope.selectedIndex = -1;
$scope.filteredOffers = [];
// $scope.link1 = [];
$scope.da = $stateParams.offer_name;
var a = $scope.da;
console.log(a);
$scope.filteredOffers = $scope.myData.filter(function(a) {
for (var i=0;i<$scope.myData.length;i++)
{
$link =$scope.myData[i].offer_name;
if (a==$link)
{
return a ;
console.log(a );
}
//console.log(a );
}
// return offer.offer_name == $scope.da;
console.log($scope.da);
});
});
/*
$scope.showData = function(offer_name, index) {
$scope.offerName = offer_name;
$scope.filteredOffers = $scope.myData.filter(function(offer) {
return offer.offer_name == $scope.offerName;
});
$scope.selectedIndex = index;
}*/
$scope.dealopen = function(a){
for (var i=0;i<$scope.myData.length;i++)
{
//console.log($scope.data[i].name);
$link=$scope.data[i].name;
console.log($link);
if ($link==$a)
{
$window.open($link,"_self","location=yes");
//console.log($a);
}
}
}
})
Html
<div ng-repeat="offer in filteredOffers">
<div class="couponCode">{{offer.coupon_code}}</div>
<div class="couponTitle">{{offer.coupon_title}}</div>
<div class="couponDescription">{{offer.coupon_Description}}</div>
</div>
You are use the Array.filter() function wrongly!
Before :
$scope.filteredOffers = $scope.myData.filter(function(a) {
for (var i=0;i<$scope.myData.length;i++)
{
$link =$scope.myData[i].offer_name;
if (a==$link)
{
return a ;
console.log(a );
}
//console.log(a );
}
// return offer.offer_name == $scope.da;
console.log($scope.da);
});
After (According to correct syntax) :
$scope.filteredOffers = $scope.myData.filter(function(a) {
if (check condition)
{
return true ;// when true is returned the json held in a gets pushed into the filteredOffers array
}
else{
return false;//when false is returned, the json held in 'a' is ignored and not pushed into the filteredOffers array
}
});
Array.filter's Doc Link
But there is something wrong with the logic that you have used. If you can tell me exactly what you are trying to do, I might be able to help you out.
If you are processing json and arrays frequently in your application, then it's better to integrate loadash or underscore in you application.
Add below code to your HTML before loading the controller file.
<script type="text/javascript" src="https://cdnjs.cloudflare.com/ajax/libs/underscore.js/1.8.3/underscore-min.js"></script>
After looking the response of http://tools.vcommission.com/api/coupons.php?apikey=e159f64e3dd49fddc3bb21dcda70f10c6670ea91aac30c7cb1d4ed37b20c45b8, below code will give you the array that matches the offer_name.
$http.get("http://tools.vcommission.com/api/coupons.php?apikey=e159f64e3dd49fddc3bb21dcda70f10c6670ea91aac30c7cb1d4ed37b20c45b8").then(function (response) {
$scope.filteredOffers = [];
var offerName = $stateParams.offer_name;
$scope.filteredOffers = _.filter(response.data, ["offer_name",offerName]);
})

How to push a JSON object to an array in AngularJS

I need to push a JSON object to AngularJS and need to check before if the value for one of the objects exist. I need to overwrite the data.
$scope.setData = function(survey, choice) {
keepAllData.push({
'surveyId': survey.id,
'choiceId': choice.id
});
console.log(keepAllData);
toArray(keepAllData);
alert(JSON.stringify(toArray(keepAllData)));
$scope.keepAllDatas.push({
'surveyId': survey.id,
'choiceId': choice.id
});
var items = ($filter('filter')(keepAllDatas, {
surveyId: survey.id
}));
}
function toArray(obj) {
var result = [];
for (var prop in obj) {
var value = obj[prop];
console.log(prop);
if (typeof value === 'object') {
result.push(toArray(value));
console.log(result);
} else {
result.push(value);
console.log(result);
}
}
return result;
}
If the survey id exists in keepalldata, I need to change the recent value with choiceid. Is it possible to do with AngularJS?
Try with this: Before pushing data you have to check if the survey id exists or not. If it exists you have to update choice with the corresponding survey id, otherwise you can push directly.
$scope.setData = function(survey, choice) {
var item = $filter('filter')(keepAllData, {
surveyId: survey.id
});
if (!item.length) {
keepAllData.push({
'surveyId': survey.id,
'choiceId': choice.id
});
} else {
item[0].choiceId = choice.id;
}
console.log(keepAllData);
}
Demo
$scope.keepAllDatas = [];
$scope.setData = function(survey, choice) {
if($scope.keepAllDatas.length == 0) {
$scope.keepAllDatas.push({'surveyId':survey.id,'choiceId':choice.id});
}
else {
var items = ($filter('filter')( $scope.keepAllDatas, {surveyId: survey.id }));
for (var i = items.length - 1; i >= 0; i--) {
// alert(items[i].surveyId);
if(items[i].surveyId == survey.id) {
console.log($scope.keepAllDatas.indexOf(survey.id));
$scope.keepAllDatas.splice($scope.keepAllDatas.indexOf(survey.id),1);
console.log("Removed data")
}
}
$scope.keepAllDatas.push({'surveyId':survey.id, 'choiceId':choice.id});
console.log( $scope.keepAllDatas)
// alert(items[0].surveyId);
}
}

Resources