Set a scope in AngularJS as a key on Firebase - angularjs

There is a way to set a $scope variable as a key on Firease?
I've tried this:
xxx.$add({
$scope.xxxx.key: {
name: $scope.xxx.name,
age: $scope.xxx.age,
email: $scope.xxx.email,
}
});
But isn't work, there is way to do that?

You can build objects with dynamic property names in javascript like this:
var newEntry = {};
newEntry[$scope.xxxx.key] = {
name: $scope.xxx.name,
age: $scope.xxx.age,
email: $scope.xxx.email,
};
xxx.$add( newEntry );

Related

Unexpected token o in JSON at position 0 at JSON.parse using angular

I have looked at simular threads, but to no success. What I'm trying to do is update my localstorage through an update function. The functions look as follows:
The code to make the variables to call:
var localProfile = JSON.parse(localStorage.getItem("profile"));
if(localProfile != undefined && localProfile.length>0)
{ this.profiles = localProfile; }
else {
this.profile = [
{ id: "1526", name: "berserk", password: "berserk", age: "31", gender: "male"},
{ id: "1358", name: "Johnathan", password: "test", age: "17", gender: "male"},
{ id: "2539", name: "Britney", password: "test", age: "18", gender: "female"},
{ id: "1486", name: "Kevin", password: "test", age: "7", gender: "male"},
{ id: "7777", name: "jesus", password: "holy", age: "unknown", gender: "male"},
{ id: "6666", name: "satan", password: "hell", age: "unknown", gender: "unknown"}
];
}
The code to update the variable:
this.updateProfile = function(profile) {
profile.updating = false;
console.log(profile);
localStorage.setItem("profile", profile);
}
As I noted in the title I am currently using Angular. I have used the console.log(-line and the response seems to be exactly what it's supposed to be. I have tried using JSON.parse( and JSON.stringify as well as a couple of other combinations. I seem to get either the error above or another error when trying to reload the page. Apperently I either cannot execute the statement, or I end up corrupting the data so reloading the page returns a simular error.
In case the data in variable profile is in doubt:
Array [ Object, Object, Object, Object, Object, Object ]
And when taking a closer look at the data:
age:"17"
gender:"male"
id:"1358"
name:"johnathan"
password:"test"
The other object looks identical with no weird defaults in them. I already took care of the $$hashkey just incase that was the problem.
Any help on how to execute the call correctly is greatly apreciated and if the information is insufficient please do tell.
The problem is your not using JSON.stringify when saving your data. So when you are parsing from localStorage its not json.
Add a factory to be used across your application that handles JSON.parse() and JSON.stringify()
.factory('LocalStorageUtil', function() {
return {
get: get,
set: set,
remove: remove
}
function get(key) {
return JSON.parse(localStorage.getItem(key));
}
function set(key, val) {
localStorage.setItem(key, JSON.stringify(val));
}
function remove(key) {
return localStorage.removeItem(key);
}
})
Here is a JS Bin tiny sample app using this LocalStorageUtil.
http://jsbin.com/fijagiy/2/edit?js,output

Store array to session storage with ngStorage

I could use some help on how i could store an array to the session storage:
So i have a json object that returns this
Object
Objectauthority: "USER_ROLE"
email: "1#1"
enabled: true
firstName: "1"
id: 1
lastName: "1"
password: "$2a$10$qPjtVDxkCh3KaE2mr0.ZeuyyjceLy7JPVmelttVf7uekSQq01fZ9u"
but it has also returns a client list
clientList: Array[7]
city: "Brussel"
company: "John Doe's coffee shop"
country: "Belgium"
...
This is the angularjs code
$http.get('/api/getuser').success(function(data) {
$scope.userdata = data;
console.log(data)
//Here we add all the stuff we need to the sessionStorage
$sessionStorage.userid = data.id;
$sessionStorage.userEmail = data.email;
$sessionStorage.sampleString = "This is a sample string";
//But how can i store the array to the sessionStorage ?
//Is something like this possible ?
$sessionStorage.clientArray[] = data.clientList[]
})
Ok i have it working i only needed to remove the [] So something like this works :
$sessionStorage.clientArray = data.clientList

Angular Shorthand on $scope for saving data

is there any shorthand for something like this?
var data =
{
name: $scope.admin.name,
email: $scope.admin.email,
roles: $scope.admin.roles
};
Usually after i query and input to model i can just use like this:
$scope.admin = {
name: value1,
email: value2,
roles: value3
}
Edited:
My exact question inside var data how can i make it more simple like above without keep typing "$scope.admin".
Thanks
If you do not want a deep copy with angular.copy(), but just want to type less signs in code, you can do
var x = $scope.admin;
var data =
{
name: x.name,
email: x.email,
roles: x.roles
};
If you need to copy all the properties, use angular.copy:
angular.copy($scope.admin, $scope.user)
If you need to pick a subset of properties, a library like lodash might be useful. You would use the pick function:
$scope.admin = {
firstname: 'John',
name: 'Doe',
email: 'john#mycompany.com',
roles: ['sysadmin']
};
$scope.user = _.pick($scope.admin, ['name', 'email', 'roles']);
// -> {name: 'Doe', email: 'john#mycompany.com', roles: ['sysadmin']}

Mongoose Schema. How to create default value for a object of object?

Meet my UserModel:
var UserModel = mongoose.model('UserModel',
{
username: { type: String, default: 'Nameless'},
password: String,
registry: String,
});
I want to do something like this to my username key:
username: {
description: {type: String, default: 'Name'},
value: {type: String, default: 'Nameless'}
};
My goal is to use this keys in a ng-repeat, so I can do something like this:
<p> {{ user.username.desc }}: {{ user.username.value }} </p>
With output: Name: Nameless
My problem is: I should be doing something wrong. I'm receiving syntax errors and my server dont even start.
:)
You can set default with a function, so create one, also you can use preSave to validate your model like:
UserModel.pre('save', function(next) {
var self = this;
// validate username field here
});
}
more info here http://mongoosejs.com/docs/middleware.html

Sorting a nested array from model in Ember?

So I have a model in Ember that is generating a hash with three objects. One of the objects is an array of objects with another array inside each object. I need to sort this innermost array, but I am having trouble doing so.
Here are my models.
App.Person = DS.Model.extend ({
first_name: DS.attr('string'),
last_name: DS.attr('string'),
age: DS.attr('string'),
gender: DS.attr('string'),
innerMostArray: DS.hasMany('innerMostObject')
});
App.innerMostObject = DS.Model.extend ({
person_id: DS.belongsTo('person'),
attr1: DS.attr('string'),
attr2: DS.attr('string')
});
Here is my Route
App.NestedArrayRoute = Ember.Route.extend({
model: function(params) {
return Ember.RSVP.hash({
object1: this.store.find('object1', params.object1_id),
people: this.store.all('person'),
object3: this.store.all('object3')
});
},
afterModel: function(model, transition) {
model.people.forEach(function(item, index, enumerable){
var innerMostArray = item.get('innerMostArray');
var sortedArray = innerMostArray.sortBy('attr1', 'attr2');
});
model.people.update();
}
});
I know that I am nowhere near doing this right but I just don't know how to sort this nested array. I've seen examples of array controllers, but I don't know how to use one to sort this nested array. If anyone could give an example of how to do this it would be very helpful. Thank you.
I agree with Kalmans answer, but I suggest you do this sorting with built-in methods to save you trouble:
App.Person = DS.Model.extend({
name: DS.attr('string'),
fruits: DS.hasMany('fruit', {async: true}),
fruitSorting: ['title', 'color'],
sortedFruits: Ember.computed.sort('fruits', 'fruitSorting')
});
I forked his example here: http://emberjs.jsbin.com/manutu/1/edit?html,js,output
One way to do this is to create a computed property on the model as follows:
App.Person = DS.Model.extend({
name: DS.attr('string'),
fruits: DS.hasMany('fruit', { async: true }),
sortedFruits: function(){
var fruits = this.get('fruits');
return fruits.sortBy('title', 'color');
}.property('fruits.#each.title', 'fruits.#each.color')
});
Working example here

Resources