I am working with angularjs. I had some different kind of issue.
I have HTTP call. after HTTP request the response will be stored in two different variable. after I change data in variable means it will change automatically into other variable also.
$http.get('get/list')
.success(function(data, status) {
$scope.test1 = data;
$scope.test2 = data;
})
.error(function(data) {
});
//sample json
{
"lists": [
{
"_id": "575e6d4bde006e3176bb9dc5",
"items": [
{
"name": "a"
}, {
"name": "b"
}
],
"name": "fridge",
"status": "done"
}
]
}
After I will push json into test1 variable.
$scope.addRow = function(comment1) {
$scope.test1.lists.push({
'name' : 'c'
});
};
But When I print the $scope.test2 it added automatically new added items also. (name = c).
Any Idea to fix this problem. I need to print test2 what getting in HTTP request.
That happened because $scope.test1 & $scope.test2 both are referring to same object in memory. Use angular.copy to create deep copy of object. So, $scope.test1 & $scope.test2 will no longer be alias of each other
$http.get('get/list')
.success(function(data, status) {
$scope.test1 = angular.copy(data);
$scope.test2 = angular.copy(data);
})
.error(function(data) {
});
Its the same relation of shallow copy / deep copy.
When you are storing values in $scope.data1 and $scope.data2, you have to make a deep copy.
Use something like this.
$scope.test1 = angular.copy(data);
$scope.test2 = angular.copy(data);
It will create a deep copy instead and changing in $scope.data1 won't effect $scope.data2
On the HTML side, you can also cut the data binding between the view and the controller by putting two ':' as a prefix of the variable. Like this :
<div>{{::test2}}</div>
It's not really like your variable won't be updated again, but the changes will not be displayed into the web page.
Related
I am running into a problem where when I submit a "property listing" I get this response:
{"owner_id":"Batman","address":"test","state":"test","sale_price":"test"}
The thing is "owner_id" is supposed to equal or associate with owner's id in a different table/JSON file (e.g owner_id = owner.id), not a string in this case which is why the object is not saving on the back-end.
Is anyone in vanilla JavaScript able to show me an example on how to associate owner_id and owner.id?
It'd be more like :
{
owner: {
id: "Batman"
},
address: "test",
state: "test",
sale_price: "test"
}
You should take a look at : https://www.w3schools.com/js/js_json_objects.asp
EDIT: Not sure how you're fetching this data but it seems like you want to handle the response you're getting.
Here is a simple GET request using the fetch api:
fetch('http://example.com/heroes') //this is the path to your source where you're getting your response data
.then((response) => {
return response.json();
//above you return a promise containing your response data
//you can also handle your response before declaring it in a var here
})
.then((myJson) => {
//you have stored your response data as a var myJson
console.log(myJson);
//here you can work your response data in any way you need
// to show an example (not that you would do this) I've provided a owner object that checks if it's property is equal to the incoming data
var owner = {
"id": Batman,
}
if ( myJson.owner_id === owner.id ) {
//do something here
}
});
More info here.
I need an advice for the best practice in order to add behavior to an object received as a json object.
I have a REST services that allow me to define a sort of state machine.
The API define a /sessions resources. When creating a session via POST /sessions/:id I get an json object in my controller:
var session = {
"id": "",
"steps": [ ... ]
}
With this object I would like it to inherit some behavior:
var baseSession = {
"nextStep": function() {... },
"getCurrentStep": function() { ...}
}
So what I would like to do is:
session.__proto__ = baseSession;
But using __proto__ seems not the thing to do.
The other possibility would be to duplicate every property in a new object:
function copyOwnProperyTo(origin, obj) {
Object.keys(origin).forEach(function(prop) {
obj[prop] = origin[prop];
});
}
var newSession = Object.create(baseSession);
copyOwnProperyTo(session, newSession);
This solution work but to me it look a bit heave. Any other suggestions?
The "proper" ES6 solution is to combine Object.assign with Object.create:
var session = Object.assign(Object.create(baseSession), {
"id": "",
"steps": […]
});
Of course you can also use your own copying method instead of Object.assign.
And finally, there is Object.setPrototypeOf, which could be used like
var session = Object.setPrototypeOf({
"id": "",
"steps": […]
}, baseSession);
I have a network array like the following way
"network_contents": [
{
"facebook":"contents to all pages",
},
{
"twitter":"twiter contents",
},
{
"linkedin":"linked in contents",
}
]
I would like to add some keys to that array bases on its content. If it is facebook the key should be facebook, if it is twitter key should be twitter. But not sure how to do it.
My requirement is to access network array contents, but it may or may not content these facebook, twitter, linked in values. I need to access its values. When i assign a key value will be easy to fetch its contents. So i tried this way to loop through the array
message.network_contents.forEach( function (nwContent) {
if(nwContent.twitter) {
console.log('nw content', nwContent.twitter);
}
})
can i create an array in this foreach loop like the following way.
{
"data": [
{
"facebook": {
"facebook": "facebook content"
},
"twitter": {
"twitter": "twitter content"
}
}
]
}
Your help is much appreciated thanks
Implementation of what I said in the comment:
var oldsies = stuff.network_contents;
var newsies = stuff.network_contents = {};
oldsies.forEach(function(network) {
var name = Object.keys(network)[0];
newsies[name] = network;
});
You gave an example of a JS object and not a dictionary and therefore cant add key-values.
You need something like this:
var network_contents = [];
network_contents["facebook"] = {config1: {name:"config1", value:"value1"}};
network_contents["twitter"] = {config2: {name:"config2", value:"value2"}};
example:
network_contents["facebook"].config1.value; // will return "value1"
You can covert your object to a dictionary easily.
I've been scratching my head with this for the last day.. hope someone can shed some light. I have a simple javascript object -- data -- JSON.stringify(data) returns it like this;
{
"dataList": [
{
"Id": 0,
"Name": "0",
},
{
"Id": 1,
"Name": "1",
}
]
}
I also have a really simple knockout viewmodel;
var viewModel = {
dataList: ko.observableArray([])
};
I then do a simple knockout.JS mapping call as per the doc site;
ko.mapping.fromJS(data, viewModel);
I would expect my viewModel to now have a dataList member (it does) that is an array of 2 (it isn't!). Instead I get an empty array.. What am I missing in the mapping here??
You shouldn't need to define the properties on your viewModel object; the mapping plugin will create them for you. Just declare viewModel as such:
var viewModel = ko.mapping.fromJS(data);
http://jsfiddle.net/vqaVT/
You only need to make the other call, ko.mapping.fromJS(data, viewModel), when you need to update your viewModel with updated data from the server.
suppose I have a config javascript file:
window.Config = {};
Config.UI = {
"Area": {},
"Layer": {},
"Sprites": {},
"Audio": {}
};
Config.UI.Area = {
"prop": {
"uuid": {
"_type": "string",
},
"frame": {
"_type": "rect",
"_value": {
"x": "0",
},
"_aka": "frame"
},
"zIndex": {
"_type": "string",
}
},
then I want use $.ajax to read this file:
$.ajax({
url:'js/config.js',
success:function (data, textStatus) {
console.log(data);
}
})
the question is how can I get some key's value in the config,by use the data $.ajax return?
like the "Config.UI" or the 'uuid' in ui.area.prop?Or can I convert them to json?
Rather than use AJAX, why not just insert a script?
var script = $('<script>');
script.attr('type', 'text/javascript');
script.attr('src', 'js/config.js');
script.bind('load', function() {
// use window.Config
});
script.appendTo('head');
icktoofay has a good suggestion, and the issue with the jQuery.ajax call looks to be a missing dataType: 'script' option which will evaluate the response and should give you object access. You might want to look into jQuery.getscript() as well.
I find it very useful and powerful to store data on the server as javascript objects and read them using Ajax. And it is very easy to do. Let me give you an example from an educational application I have written.
This is an example table of contents file (l1contents.js) that I would store on the server:
{
title : "Lesson 1",
topics : [
{name : "Topic 1", file : "l1t1data.js" },
{name : "Topic 2", file : "l1t2data.js" },
]
}
This is the javascript code I use to process the file:
$.ajax({
url : contentsFileName, // would be set to 'l1contents.js'
dataType : 'text', // yes this is correct, I want jquery to think this is text
cache : false,
success: function(data) {
var contentsObj = eval('(' + data + ')');
var lessonTitle = contentsObj.title;
for (var i = 0; i < contentsObj.topics.length; i++) {
var topic = contentsObj.topics [i];
// process topic.name and topic.file here
}
}
});
Obviously, this is simplified, but hopefully you get the idea. I simply use eval to set the object. And note that I don't even need any javascript code defining the structure of contentsObj. (I, of course, do have extensive comments defining the structure of my objects, but they are simply comments, not code.)
if your json file contains json data than you can use parseJSON() , toJSON() method.
and another solution is use eval(), this conver json data to javascript object so you can easly get a value by giving key.