I'm trying to map some data (returned from a jQuery $.ajax call) to a view model, but for some reason the nested array is not mapped.
<p>Name: <input data-bind="value: Name" /></p>
<p>Age: <input data-bind="value: Age" /></p>
<p>Friends: <span data-bind="text: Friends.length"></span></p>
<script type="text/javascript">
var viewModel = null;
var data = { "Name": "Simon", "Age": "24", "Friends": [{ "Name": "Bill", "Age": "24" }, { "Name": "Peter", "Age": "21"}]};
viewModel = ko.mapping.fromJS(data);
ko.applyBindings(viewModel);
</script>
In this simple example Simon has no friends...
mapping.fromJS converts arrays to observable arrays, so Friends is an observable array and to access its underlying javascript array you need to call it: Friends().length
Related
I have a custom directive that is holding an array of JavaScript objects.
The object is a little complex and lengthy but I will display something similar to point out my problem:
A JSON.stringify of this displays the following:
[
{
"Id": 1,
"Name": "John Doe",
"EMail": "john#doe.com"
},
{
"Id": 2,
"Name": "Jim Doe",
"EMail": "jim#doe.com"
},
{
"Id": 3,
"Name": "Jeff Doe",
"EMail": "jeff#doe.com"
}
]
I am further using ng-repeat to display the values in a tabular form on my HTML.
The values are coming from an API call that fetches them from a database.
I want to swap - say the entire Object with Id 1 with the entire Object with Id 3 so that during my tabular display I can see Id 3 object details first and Id 1 object details last, without breaking any functionality.
What would be the best possible solution to do this within the frontend itself?
How about just swapping them using a temp variable?
var arr = [{"Id":1,"Name":"John Doe","EMail":"john#doe.com"},
{"Id":2,"Name":"Jim Doe","EMail":"jim#doe.com"},
{"Id":3,"Name":"Jeff Doe","EMail":"jeff#doe.com"}]
var tmpObj = arr[0];
arr[0] = arr[2];
arr[2] = tmpObj;
If you want to reverse the array, use Array.prototype.reverse()
var app = angular.module("myApp", []);
app.controller("myController", function($scope) {
var arr = [
{
"Id": 1,
"Name": "John Doe",
"EMail": "john#doe.com"
},
{
"Id": 2,
"Name": "Jim Doe",
"EMail": "jim#doe.com"
},
{
"Id": 3,
"Name": "Jeff Doe",
"EMail": "jeff#doe.com"
}
];
$scope.array = arr.reverse();
});
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.6.0/angular.min.js"></script>
<div ng-app="myApp">
<div ng-controller="myController">
<div ng-repeat="item in array">
{{item.Id}} - {{item.Name}} - {{item.EMail}}
</div>
</div>
</div>
I have two file, a JSON storing some data and a simple html form.
I want to fill the form with random data taken from a JSON. Those data should be relative to the same object.
My form looks like:
<form id="first_form">
Name:<br>
<input id="name" type="text" name="name">
<br>
Phone:<br>
<input id="phone" type="number" name="phone">
<br>
City:<br>
<input id="city" type="text" name="city">
<br>
Pcode:<br>
<input id="pcode" type="number" name="pcode">
Note:<br>
<input id="note" type="text" name="note">
<br>
</form>
My JSON looks like:
users: [
{
"name": "name1",
"phone": "111111111",
"address": "address1",
"city": "city1",
"pcap": 1111,
"note": ""
},
{
"name": "name2",
"phone": "222222222",
"address": "address2",
"city": "city2",
"pcap": 2222,
"note": ""
},
{
"name": "name3",
"phone": "333333333",
"address": "address3",
"city": "city3",
"pcap": 3333,
"note": ""
},
{
"name": "name4",
"phone": "44444444",
"address": "address4",
"city": "city4",
"pcap": 4444,
"note": ""
}
]
Is there a way to do so in a no-jQuery way?
I hope it is users = rather than users :. Also change id 'pcode' to 'pcap'
In that case you can use the following code
var indx = Math.floor(Math.random()*users.length);
var randUser = users[indx];
for(prop in randUser) {
document.getElementById(prop).value = randUser[prop];
}
There are non-jquery (or other framework) ways to do this, but they are quite tedious (thats why these frameworks exists).
In addition: How would your fill a "single" form with an ARRAY of objects? you will either need to repeat the form or have some way of selecting which dataset you want.
One easy way to fill a form from a json is https://github.com/corinis/jsForm
(disclaimer: I am the author of that module)
If you really want to do it the hard way I suggest taking a close look at http://www.w3schools.com/js/js_htmldom.asp
You need to start processing the complete DOM and identify which form-fields match input and have to worry about the cross-browser dom implementation issues.
Basically you start with getting the "root" of where you want to start parsing:
var root = document.getElementById("first_form");
and then have a recursive function that goes through all children and its childrent to identify a form, which you can then check against your object:.
function replace(root, obj) {
var children = root.childNodes;
for(var i = 0; i < children.lenght; i++) {
var child = children[i];
// go deep
if(child.children) {
replace(child, obj);
}
// check if we have a name attribute - then assume its a form and set its value
if(child.getAttribute("name")) {
child.setAttribute("value", obj[child.getAttribute("name")]);
}
}
}
You can extend the code to also allow sub-objects or other peculiarities in your object.
Going the other way round (doing a for-in in your object and searching for fields) also works and is less code, but that only works for very simple objects.
I have an object and within this object I have items and one of the items is an array which also contains objects. A sample of the data is shown below.
I am using knockout to bind this data to the view so I think I need to implement a double loop for returning the objects and the objects within the child array to be able to bind them in the view.
Sample data:
"singers": {
"ijiyt6ih": {
"id": ObjectId('ijiyt6ih'),
"name": "John",
"songs": [
{
"id": ObjectId('okoiu8yi'),
"songName": "Hello There",
"year": "1980"
},
{
"id": ObjectId('sewfd323'),
"songName": "No More",
"year": "1983"
}
]
},
"98usd96w": {
"id": ObjectId('98usd96w'),
"name": "Jack",
"songs": [
{
"id": ObjectId('iew342o3'),
"songName": "Hurry Up",
"year": "1985"
}
]
}
}
I need to find a way to appropriately loop through this so that I can modify the returned data to bind it to the viewModel using knockout.
Here is how my viewModel looks like:
singersViewModel = function(data) {
var self = {
singerId: ko.observable(data.id),
singerName: ko.observable(data.name),
songName: ko.observable(...),
songYear: ko.observable(...)
};
I am not sure if I will have to return two different sets of data or not.
As for the looping. I was able to loop and return the list of singers to display on the page but I am not able to get the list of songs displayed within each singer.
Here is my loop so far:
var self = {},
singer,
tempSingers = [];
self.singers = ko.observableArray([]);
for (singer in singers) {
if (singers.hasOwnProperty(singer)) {
tempSingers.push(new singersViewModel(singers[singer]));
}
}
self.singers(tempSingers);
I tried to duplicate the same type of loop for songs within this loop but i would get an error using hasOwnProperty because songs is an array.
In the included snippet you can see how you can map the original data to a viewmodel that can be bound to a view.
I've left the ids as regular properties, and converted the names into observables, so thatthey can be edited. At the bottom you can see the current viewmodel state.
There is also a sample view which iterates the list of singers, and also the list of song within each singer.
As you can see I'm implementing the solution using mapping. For mapping you need to implement a callback that receives each original object and returns a new one with a new structure. For example this part of the code
_.map(_singers, function(singer) {
return {
id: singer.id,
name: ko.observable(singer.name),
// ... songs:
})
iterates over each singer (the sample data in the question), and for each one creates a new object with the id, an observable which includes the name (and the mapping of songs, which I don't show in this fragment).
NOTE: I'm using lodash, but many browsers support map natively as an array function
var ObjectId = function (id) { return id; }
var singers = {
"ijiyt6ih": {
"id": ObjectId('ijiyt6ih'),
"name": "John",
"songs": [
{
"id": ObjectId('okoiu8yi'),
"songName": "Hello There",
"year": "1980"
},
{
"id": ObjectId('sewfd323'),
"songName": "No More",
"year": "1983"
}
]
},
"98usd96w": {
"id": ObjectId('98usd96w'),
"name": "Jack",
"songs": [
{
"id": ObjectId('iew342o3'),
"songName": "Hurry Up",
"year": "1985"
}
]
}
};
var SingersVm = function(_singers) {
var self = this;
self.singers = _.map(_singers, function(singer) {
return {
id: singer.id,
name: ko.observable(singer.name),
songs: _.map(singer.songs, function(song) {
return {
name: ko.observable(song.songName),
id: song.id
};
})
};
});
return self;
};
var vm = new SingersVm(singers);
//console.log(vm);
ko.applyBindings(vm);
<script src="https://cdnjs.cloudflare.com/ajax/libs/lodash.js/3.10.1/lodash.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/knockout/3.2.0/knockout-min.js"></script>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div data-bind="foreach: singers">
<div>
<input data-bind="value: name"/> (<span data-bind="text: id"></span>)
<ul data-bind="foreach:songs">
<li>
<input data-bind="value: name"/> (<span data-bind="text: id"></span>)
</li>
</ul>
</div>
</div>
<pre data-bind="html: ko.toJSON($root,null,2)">
</pre>
fiddle here http://jsfiddle.net/prantikv/1nvdzv24/9/
i have some uneven data like so
[{
"fname": "Tonja", //common
"lname": "Mize",
"tel": "(963)784-1098",
"address": "3999 Quis Ln",
"city": "Sebring",
"state": "MI",
"zip": 76593
},
{
"fname": "Stella", //common
"Othername": "Lester",
"mobile": "(936)898-2886"
}];
notice only the fname property is common between the two objects
so when i do this
<li ng-repeat="(key,val) in populationList | filter:name">
{{ val.**fname**}}
</li>
i do get the fname but the data is uneven so i cannot figure out how to go through over each object. also the length of the object is different as well.
what i want to do is to filter the data over a select list
<select ng-model="name">
<option value="Tonja" selected="Tonja">Tonja</option>
<option value="Stella">Stella</option>
</select>
but i am unable to figure out a way to display the unmatched properties of objects
is there a way i get all the key:value pairs on the sub data dynamically?
WORKING DEMO
Your Html,
<div ng-app='app'>
<div ng-controller="DemoCtrl">
<select ng-options="item.fname for item in populationList | fieldList:'fname'" ng-model="myItem" ng-change="changeSelection(myItem)">
</select>
<li ng-repeat="key in availableKeys">
{{selectedObject[key]}}
</li>
</div>
</div>
JS
angular.module('filters',[]).
filter('fieldList', function() {
return function(populationList, parameter) {
var filteredArray = [];
angular.forEach(populationList, function(value, index) {
if(value.hasOwnProperty(parameter)) {
filteredArray.push(value);
}
});
return filteredArray;
};
});
angular.module('app',['filters'])
.controller('DemoCtrl', function($scope) {
$scope.changeSelection = function(item) {
$scope.selectedObject = item;
$scope.availableKeys = Object.keys($scope.selectedObject);
};
$scope.populationList = [{
"fname": "Tonja", //common
"lname": "Mize",
"tel": "(963)784-1098",
"address": "3999 Quis Ln",
"city": "Sebring",
"state": "MI",
"zip": 76593
},
{
"fname": "Stella", //common
"Othername": "Lester",
"mobile": "(936)898-2886"
}];
});
I am reading the below json value from a module.js
.controller('home.person',['$scope','$filter','personResource',function($scope,$filter,personResource) {
$scope.searchPerson = function() {
var params = $scope.search || {};
params.skip=0;
params.take =10;
$scope.personDetails =
{
"apiversion": "0.1",
"code": 200,
"status": "OK",
"mydata": {
"myrecords": [
{
"models": [
{
"name": "Selva",
"dob": "10/10/1981"
}
],
"Address1": "ABC Street",
"Address2": "Apt 123",
"City": "NewCity1",
"State": "Georgia"
},
{
"models": [
{
"name": "Kumar",
"dob": "10/10/1982"
}
],
"Address1": "BCD Street",
"Address2": "Apt 345",
"City": "NewCity2",
"State": "Ohio",
"Country":"USA"
},
{
"models": [
{
"name": "Pranav",
"dob": "10/10/1983"
}
],
"Address1": "EFG Street",
"Address2": "Apt 678",
"City": "NewCity3",
"State": "NewYork",
"Country":"USA",
"Zipcode" :"123456"
}
]
}
}
}
}])
Now i am able to statically build the UX. But my each record set's key value pair count is different. So i want to build my html dynamically as per the current record set's count.Country & Zipcode is not exist in all records so i need to build dynamically the build and populate the html output.Most of the time, my json output is dynamic. Instead of persondetails, i may get the json output of a product details instead of PersonDetails.
<div ng-show="personDetails.mydata.myrecords.length > 0" ng-repeat="recordSingle in personDetails.mydata.myrecords">
<div >
<span >Address1: {{recordSingle.Address1}}</span>
<span >Address2: {{recordSingle.Address2}}</span>
<span>City: {{recordSingle.City}}</span>
<span>State: {{recordSingle.State}}</span>
<span>Country: {{recordSingle.Country}}</span>
<span>Zipcode: {{recordSingle.Zipcode}}</span>
</div>
</div>
One way is to use ng-if statement, for the optional span elements:
<span ng-if="recordSingle.Address1">Address1: {{recordSingle.Address1}}</span>
[Update #1: updated based on revised comments to question]
[Update #2: fixed typos in function and included plunkr]
I now understand that you want to dynamically build the display objects based on properties from the JSON object. In this case, I would iterate through the properties of the object. I would use a function to produce this array of properties for each object so that you can filter out any prototype chains. I would also remove out any unwanted propoerties, such as the internal $$hashKey and perhaps the array objects e.g.
In your controller:
$scope.getPropertyNames = getPropertyNames;
function getPropertyNames(obj) {
var props = [];
for (var key in obj) {
if (obj.hasOwnProperty(key) && !angular.isArray(obj[key]) && key !== '$$hashKey') {
props.push(key);
}
}
return props;
}
Then in your HTML view:
<div ng-repeat="record in personDetails.mydata.myrecords">
<div ng-repeat="prop in getPropertyNames(record)">
<span ng-bind="prop"></span>: <span ng-bind="record[prop]"></span>
</div>
</div>
This works for me... see this plunker. It is displaying each of the properties of the object in the array dynamically (you could have any property in the object). Is this not what you are trying to achieve?