Angular Shorthand on $scope for saving data - angularjs

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']}

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

Set a scope in AngularJS as a key on Firebase

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 );

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

location object expected, location array not in correct format

I have spent doing such a straight forward thing. I just want to do a CRUD operation on a user model using nodejs, mongoose, restify stack. My mongo instance is on mongolab.
The user should contain a "loc" field . User schema is as follows :
var mongoose = require('mongoose')
var Schema = mongoose.Schema;
var userSchema = new Schema( {
email_id : { type: String, unique: true },
password: { type: String},
first_name: String,
last_name: String,
age: String,
phone_number: String,
profile_picture: String,
loc: {
type: {},
coordinates: [Number]
}
});
userSchema.index({loc:'2d'});
var User = mongoose.model('user', userSchema);
module.exports = User;
the rest api used to post is as follows :
create_user : function (req, res, next) {
var coords = [];
coords[0] = req.query.longitude;
coords[1] = req.query.latitude;
var user = new User(
{
email_id : req.params.email_id,
password: req.params.password,
first_name: req.params.first_name,
last_name: req.params.last_name,
age: req.params.age,
phone_number: req.params.phone_number,
profile_picture: req.params.profile_picture,
loc: {
type:"Point",
coordinates: [1.0,2.0] // hardcoded just for demo
}
}
);
user.save(function(err){
if (err) {
res.send({'error' : err});
}
res.send(user);
});
return next();
},
Now when i do a POST call on curl -X POST http://localhost:3000/user --data "email_id=sdass#dfAadsfds&last_name=dass&age=28&phone_number=123456789&profile_picture=www.jakljf.com&longitude=1.0&latitude=2.0"
I get the following error
{
error: {
code: 16804
index: 0
errmsg: "insertDocument :: caused by :: 16804 location object expected, location array not in correct format"
op: {
email_id: "sdass#dfAadsfdsadkjhfasvadsS.com"
password: "sdass123DadakjhdfsfadfSF45"
first_name: "shaun"
last_name: "dass"
age: "28"
phone_number: "123456789"
profile_picture: "www.jakljf.com"
loc: {
coordinates: [2]
0: 1
1: 2
-
type: "Point"
}-
_id: "55efc95e0e4556191cd36e5e"
__v: 0
}-
}-
}
The location field is giving problems as the POST call works just fine if i remove the loc field from model
Below are the hits/trials I did :
1) Change userSchema.index({loc:'2d'}); to userSchema.index({loc:'2dsphere'});
2) Changing loc schema to everything given in Stackoverflow. I would like to know the right way to define this though.
3) Passing the hardcode 2d array but still it says Location object expected, location array not in correct format" what format is required for this ?
Any help in this regard is greatly appreciated. Thanks.
MongoDB 2d index requires the legacy coordinates pairs format, which is just an array of coordinates like [1, 2].
If you need GeoJSON support, please use the 2dsphere index.
userSchema.index({loc:'2dsphere'});
If you are using Spring Boot make sure you set the index type to 2DSphere:
#GeoSpatialIndexed(type = GeoSpatialIndexType.GEO_2DSPHERE) GeoJsonPoint location;

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

Resources