I have an ionic app in which I have 7 input fields. what I am doing is I am saving those values from input fields into localstorage. below is my code in angularjs controller :
window.localStorage.setItem('Frames', JSON.stringify(PositionFrames));
$scope.Save = function () {
var FrameValues = {
"PositionName": $scope.data.PositionName,
"box1": 'j0' + $scope.data.box1,
"box2": 'j1' + $scope.data.box2,
"box3": 'j2' + $scope.data.box3,
"box4": 'j3' + $scope.data.box4,
"box5": 'j4' + $scope.data.box5,
"box6": 'gr' + $scope.data.box6
};
var temp = [];
tmp = JSON.parse(window.localStorage.getItem('Frames'));
temp.push(tmp);
temp.push(FrameValues);
window.localStorage.setItem('Frames', JSON.stringify(temp));
// window.localStorage['Frames'] = JSON.stringify(temp)
console.log(JSON.stringify(temp));
};
Whenever I hit button to save data and print data in console.log I can see following results :
[[[{"PositionName":"Home","box1":90,"box2":90,"box3":90,"box4":90,"box5":90,"box6":90}],{"PositionName":"Amrit","box1":"j058","box2":"j161","box3":"j2143","box4":"j3152","box5":"j4157","box6":"gr159"}],{"PositionName":"Amrit","box1":"j058","box2":"j161","box3":"j2143","box4":"j3152","box5":"j4157","box6":"gr159"}]
However if you see data in not in order, I dont know why it is not in format like this [{},{},{}]. I cannot figure out where these additional [[[ are coming from.
How do I solve it ?
Thanks Fellas :)
Thanks
following solved this problem
for (i = 0; i < tmp.length; i++) { temp.push(tmp[i]) }
hope this will help someone
Related
I'm fetching a URL. The full response is spread over five pages.
I'm looping through each pages which returns me an array of object (please correct me if I'm wrong):
[{item_1=foo, item_2=bar, item_3=foobar, value_1=XX}, {item_1=bar, item_2=foo, item_3=barfoo, value_1=XX},etc...]
I want to consolidate all the response like if it was one big array of objects.
So far, I wrote this:
for (i = 1; i <= total_pages; i++) {
var rawResponse = UrlFetchApp.fetch(
'url',
{
method: 'GET'
})
response[i] = JSON.parse(rawResponse);
}
var g = response[1].concat(response[2], response[3],response[4],response[5]);
g contains the desired output; however, as you can see, this is not dynamic. How can I solve this? I could you the push method, but I would return me a new array with each response.
In order to make your code "dynamic" you could use the concat function inside the for-loop, for each of the pages. A possible modification of your code could look like the following, where the result variable would contain all the results:
var result = [];
for (var i = 1; i <= total_pages; i++) {
var rawResponse = UrlFetchApp.fetch(
'url',
{
method: 'GET'
}
);
var current = JSON.parse(rawResponse);
result = result.concat(current);
}
can anybody help me? I'm having a problem similar to the previous post. I'm just not getting the child object. I have tried in several ways the most basic and logical would be: newPost.musician.statusbatera
Follows a chrome debug print: --Screen Shot--
I'm not getting it because of the key generated automatically by firebase as the print in attached.
My code:
var db = firebase.database();
var ref = db.ref("users");
ref.on("child_added", function(snapshot) {
var newPost = snapshot.val();
console.log("Musician: " + newPost.musician.statusbatera);
});
You can grab the autogenerated key using Object.keys, then you can assign the object you need:
ref.on("child_added", function(snapshot) {
var newPost = snapshot.val();
keys = Object.keys(newPost.musician)
console.log("Musician: " + newPost.musician[keys[0]].statusbatera);
});
in theory, there should be only one value in keys...
I think you want to iterate through musician's list, if so, give this a try :-
for(var i = 0; i <= newPost.musician.lenght; i++) {
console.log("Musician: " + newPost.musician[i].statusbatera);
}
i have one doubt how can i pass data from one page to another page in angularjs without using localstorage and data should exist even if user reload that page.
Is there any way out from here or not?
Thank's in advance
you can use cookie's :
https://docs.angularjs.org/api/ngCookies/service/$cookies
you can refer to this JSbin link for example:
http://jsbin.com/duxaqa/2/edit
Also, there is a nice stackoverflow answer that match your needs i think, with a more complete explanation than mine:
How to access cookies in AngularJS?
You can put data to cookie
// set cookie on one page:
setCookie("key", value);
// get cookie on another page:
var val = getCookie("key");
Using functions:
function setCookie(name, value, options) {
options = options || {};
var expires = options.expires;
if (typeof expires == "number" && expires) {
var d = new Date();
d.setTime(d.getTime() + expires * 1000);
expires = options.expires = d;
}
if (expires && expires.toUTCString) {
options.expires = expires.toUTCString();
}
value = encodeURIComponent(value);
var updatedCookie = name + "=" + value;
for (var propName in options) {
updatedCookie += "; " + propName;
var propValue = options[propName];
if (propValue !== true) {
updatedCookie += "=" + propValue;
}
}
document.cookie = updatedCookie;
}
function getCookie(name) {
var matches = document.cookie.match(new RegExp(
"(?:^|; )" + name.replace(/([\.$?*|{}\(\)\[\]\\\/\+^])/g, '\\$1') + "=([^;]*)"
));
return matches ? decodeURIComponent(matches[1]) : undefined;
}
But keep in mind that cookies size limited: 4093 bytes per domain.
you can pass data to another page using $rootScope or $cookieStore. But, only $cookieStore will save data when user reload the page. Take a look how to implement example:
angular.module('cookieStoreExample')
.controller('ExampleController', function($cookieStore) {
// Put cookie
$cookieStore.put('myFavorite','oatmeal');
// Get cookie
var favoriteCookie = $cookieStore.get('myFavorite');
// Removing a cookie
$cookieStore.remove('myFavorite');
});
I've got a factory that gets my data from Firebase, and I want my controller to be able to access it. However, when I console.log the data in my controller, it isn't the Array[10] that I would expect it to be, but rather an Array with keys 0,1,2,..10, $$added, $$error, $$moved,... and so on. However, when I skip out on using the factory, and use $asArray() method on my firebase ref directly in my controller it shows up nicely as an Array[10]
In my factory, this is what it looks like..
var listingsref = new Firebase("https://something.firebaseio.com");
var sync2 = $firebase(listingsref);
var products = sync2.$asArray();
factory.getProducts = function(){
return products;
};
Controller
$scope.products = marketFactory.getProducts();
console.log($scope.products) in my controller should be Array[10], but instead it's an Array with the data + a lot more $$ methods. Anyone know what's going on? Thanks
EDIT: Full Factory File
(function(){
var marketFactory = function($firebase){
var listingsref = new Firebase("https://something.firebaseio.com");
var sync2 = $firebase(listingsref);
var products = sync2.$asArray();
var factory = {};
factory.getProducts = function(){
console.log(products);
return products;
};
factory.getProduct = function(productId){
for(var x = 0; x<products.length ;x++){
if(productId == products[x].id){
return {
product:products[x],
dataPlace:x
};
}
}
return {};
};
factory.getNextProduct = function(productId, e){
var currentProductPlace = factory.getProduct(productId).dataPlace;
if (e=="next" && currentProductPlace<products.length){
return products[currentProductPlace+1];
}
else if(e=="prev" && currentProductPlace>0){
return products[currentProductPlace-1];
}
else{
return {};
}
};
factory.componentToHex = function(c){
var hex = c.toString(16);
return hex.length == 1 ? "0" + hex : hex;
};
factory.rgbToHex = function(r,g,b){
return "#" + factory.componentToHex(r) + factory.componentToHex(g) + factory.componentToHex(b);
};
factory.hexToRgb = function(hex) {
if(hex.charAt(0)==="#"){
hex = hex.substr(1);
}
var bigint = parseInt(hex, 16);
var r = (bigint >> 16) & 255;
var g = (bigint >> 8) & 255;
var b = bigint & 255;
return r + ", " + g + ", " + b;
};
factory.parseRgb = function(rgb){
rgb = rgb.replace(/\s/g, '');
var red = parseInt(rgb.split(',')[0]);
var green = parseInt(rgb.split(',')[1]);
var blue = parseInt(rgb.split(',')[2]);
return {
r:red,
g:green,
b:blue
};
};
return factory;
};
marketFactory.$inject = ['$firebase'];
angular.module('marketApp').factory('marketFactory', marketFactory);
}());
This snippet gets a synchronized AngulareFire array of products:
var products = sync2.$asArray();
The AngularFire documentation is a bit off on this point: what you get back from $asArray() is not an array, but the promise of an array. At some point in the future your products variable will contain an array. This is done because it may take (quite) some time for your array data to be downloaded from Firebase. Instead of blocking your code/browser while the data is downloading, it returns a wrapper object (called a promise) and just continues.
Such a promise is good enough for AngularJS: if you simply bind products to the scope and ng-repeat over it, your view will show all products just fine. This is because AngularFire behind the scenes lets AngularJS know when the data is available and Angular then redraws the view.
But you said:
console.log($scope.products) in my controller should be Array[10]
That is where you're mistaken. While AngularFire ensures that its $asArray() promise works fine with AngularJS, it doesn't do the same for console.log. So your console.log code runs before the data has been downloaded from Firebase.
If you really must log the products, you should wait until the promise is resolved. You this this with the following construct:
products.$loaded().then(function(products) {
console.log(products);
});
When you code it like this snippet, the data for your products will have been downloaded by the time console.log runs.
Note that the object will still have extra helper methods on it, such as $add. That is normal and also valid on an array. See the documentation for FirebaseArray for more information on what the methods are, what they're for an how to use them.
So I edited the code in the plnkr at http://plnkr.co/M4PqojtgRhDqU475NoRY.
The main differences are the following:
// Add $FirebaseArray so we can extend the factory
var marketFactory = function($firebase, $FirebaseArray){
var listingsref = new Firebase("https://something.firebaseio.com");
// Actually extend the AngularFire factory and return the array
var MarketFactory = $FirebaseArray.$extendFactory(factory);
return function() {
var sync = $firebase(listingsref, {arrayFactory: factory});
return sync.$asArray();
};
Check out https://www.firebase.com/docs/web/libraries/angular/guide.html#section-extending-factories for more information on extending AngularFire entries. You will likely need to make some adjustments to the rest of the factory code.
I have integrated SlickGrid with my Angular JS application. Earlier I was populating the Grid Data with plain hardcoded javascript code[see below]. But now I need to get the grid data from REST service which is invoked in my angular Js Controller and saved in an object array. How do I access a variable[array] defined in angular js inside my SlickGrid javascript code.
I tried replacing 'data' below with the array defined in angular js code but it's not working. Can anyone please help me here.
$(function () {
/* need to comment out this code once I can use the array defined in angular Js */
var data = [];
for (var i = 0; i < 500; i++) {
data[i] = {
title: "Task " + i,
duration: "5 days",
percentComplete: Math.round(Math.random() * 100),
start: "01/01/2009",
finish: "01/05/2009",
effortDriven: (i % 5 == 0)
};
}
grid = new Slick.Grid("#myGrid", data, columns, options);
})
Update: This is my slickgrid code. I am invoking a REST service to get the data in $scope.data1 and then using it to populate the slickgrid but I am getting an empty slickgrid. But if I hardcode the data in $scope.data1 , it works. What I am missing? Can anyone please help me. I have spent an entire day on this issue.
$scope.populateGridData = function()
FetchPopulation.get({id:1} , function(response ) {
$scope.data1 = [];
for (var i = 0; i < response.PopulationList.population.length; i++)
$scope.data1[i] = {
firstName: response.PopulationList.population[i].firstName,
lastName: response.PopulationList.population[i].lastName,
designation: response.PopulationList.population[i].designation,
department: response.PopulationList.population[i].department,
salary: response.PopulationList.population[i].salary,
rating: response.PopulationList.population[i].rating,
joiningDate: response.PopulationList.population[i].joiningDate,
employeeId: response.PopulationList.population[i].employeeId,
employeeType: response.PopulationList.population[i].employeeType,
manager: response.PopulationList.population[i].manager,
permanent: (i % 5 == 0),
percentComplete: Math.round(Math.random() * 100)
};
/*
$scope.data1= [{employeeId:"12345", firstName: "aaa", lastName: "bbb" , designation:"Business Analyst" , department:"FSI" ,
salary:"120000",rating:"1" , joiningDate:"12/8/2013" , employeeType:"permanent" , manager:"aaaa" }];
*/
var grid = new Slick.Grid("#myGrid", $scope.data1, $scope.columns, $scope.options);
$scope.grid.setSelectionModel(new Slick.CellSelectionModel());
});
};
Did you type by hand the commented line there? Because it's not valid JSON, everything has to be escape [{employeeId:"12345" should be [{"employeeId":"12345",... and even if it's not that, your dataset seems wrong. I am not using SlickGrid without the DataView as you are doing but if you take the basic example and copy this piece of code (pulled from SlickGrid example2:
$(function () {
for (var i = 0; i < 5; i++) {
var d = (data[i] = {});
d["title"] = "<a href='#' tabindex='0'>Task</a> " + i;
d["duration"] = "5 days";
d["percentComplete"] = Math.min(100, Math.round(Math.random() * 110));
d["start"] = "01/01/2009";
d["finish"] = "01/05/2009";
d["effortDriven"] = (i % 5 == 0);
}
grid = new Slick.Grid("#myGrid", data, columns, options);
})
it will most probably work... Try this piece out before going back to your code, but I strongly suspect your JSON result might not be valid as you think it is... now after you tried the basic sample and you go back to your code, you could try to validate your JSON output by going here: JSONLint just copy+paste your JSON in there and click validate.