I'm new to front end development and am playing with angular.js (1.4.8). In the code below, I do an http get. I then
map the json data into a table. I think I have a mapping problem, ie, the ng-repeat isn't pulling stuff out of the
json correctly. Or perhaps it's something else and I'm unintentionally misleading you. Do you see a programming
error here?
Here is the relevant html:
<div class="table-responsive" data-ng-app="myApp" data-ng-controller="customersCtrl">
<table class="table table-striped">
<thead>
<tr>
<th data-ng-repeat="header in headers">{{header}}</th>
</tr>
</thead>
<tbody>
<tr data-ng-repeat="record in records track by $index">
<td>{{ record.data.day }}</td>
<td>{{ record.data.date }}</td>
<td>{{ record.data.value }}</td>
</tr>
</tbody>
</table>
</div>
Here is my angular file:
var app = angular.module('myApp', []);
app.controller('customersCtrl', function ($scope, $http) {
$scope.init = function () {
$http.get("https://localhost:4567/1")
.then(function (response) {
var json = angular.toJson(response.data.records);
$scope.records = json;
$scope.headers = response.data.headers;
});
};
$scope.httpPost = function (journal) {
var theJson = angular.toJson(journal);
var successCallback = function (data, status, headers, config) {
$scope.postResponse = data;
};
var errorCallback = function (data, status, headers, config) {
console.log();
};
$http.post('https://localhost:4567/journal', {"foo": "bar"}).then(successCallback, errorCallback);
};
$scope.master = {};
$scope.update = function (journal) {
$scope.master = angular.copy(journal);
};
$scope.reset = function () {
$scope.journal = angular.copy($scope.master);
};
$scope.init();
$scope.reset();
});
Here is the response body (json):
{
"headers" : [ "day", "date", "value" ],
"records" : [ {
"data" : {
"day" : "Tuesday",
"date" : "5/3/2011",
"value" : "2.6"
},
"id" : "646312cc-1931-4137-af2a-e712300b489b",
"dateCreated" : 1453842720871,
"dateUpdated" : 1453842720871,
"etag" : "3bee5500-fd03-4d69-84af-8b8dc85292b0"
}, {
"data" : {
"day" : "Wednesday",
"date" : "5/4/2011",
"value" : "2.6"
},
"id" : "f58eae54-6b30-4f61-b8cc-b04984a8436a",
"dateCreated" : 1453842720871,
"dateUpdated" : 1453842720871,
"etag" : "29e4dc69-c118-4fad-91ae-8a1efaf9b984"
}, {
"data" : {
"day" : "Thursday",
"date" : "5/5/2011",
"value" : "2.6"
},
"id" : "ebf8dba4-52a9-4e0b-a575-cda2ea29a2ea",
"dateCreated" : 1453842720871,
"dateUpdated" : 1453842720871,
"etag" : "986961bb-84ff-4ac6-9f70-96827006ed87"
} ],
"id" : null,
"dateCreated" : null,
"dateUpdated" : null,
"etag" : null
}
=====
As pointed out by two people, the problem was this line (I had turned json object to debug something and forgot to revert ;(
var json = angular.toJson(response.data.records);
Angular's $httpProvider automatically adds the Content-Type: application/json header to all outgoing service requests made by your application.
In addition, it will also automatically deserialise responses using a JSON parser if a JSON-like response is detected.
As such, there is no need to use functions like angular.toJson() to do the JSON conversion yourself unless you have overridden the default provider behaviour somewhere.
Glad that helped. :-)
Related
this is the value i'm sending through postman tool
{
"name" :[
{
"first_name" : "antony",
"second_name" : "grijan"
},{
"first_name" : "suresh",
"second_name" : "muthu"
}],
"allergy" : [
{
"condition" : "headache"
},
{
"condition" : "toothache"
}],
"communication" : [
{
"address" : "no 21 big street",
"phone" : "84"
},
{
"address" : "no 43 small street",
"phone" :"87"
}]
}
I got the value in my control layer and i'm trying to save it in my mongodb using mongoose, my model code is
var mongoose = require('mongoose');
var Schema = mongoose.Schema;
var patientSchema = new Schema({
name: {
first_name : { type : String, default : ''},
second_name : { type : String, default : ''}
},
allergy : {
condition : {type : String, default : ''}
},
communication : {
address : {type : String, default : ''},
phone : {type : String, default : ''}
}
});
var patients = mongoose.model('Patients',patientSchema);
module.exports = patients;
My service layer code where i'm iterating is
var addDao = require('../dao/dao');
var async = require('async');
module.exports.addPatient = function(detail,callback) {
async.mapValues(detail,function(value,key,callback){
addDao.addPatient(value,function(data){
console.log(data);
console.log("calling");
callback(null, data);
})
}, function(err, result) {
// result is now a map of results for each key
console.log("inside func",result);
callback(result);
}
);
}
I have a console.log() in my service layer but it gives me only empty values, i think there is something wrong either with my model code or my iteration in my service layer!
I created function which is adding people_id inside array of given card. But there is problem that inserted id is always not as an objectId() where I just need it to be saved as objectId.
When id is added to array i I'm sending whole variable board JSON to nodejs API where is executed function findOneAndUpdate. And here is problem because after saved this arrays is not objectID in Author. Can someone tell me how to make it?
JSON board
{
"_id" : ObjectId("59e096a7622a3825ac24f343"),
"name" : "1",
"users" : [
ObjectId("59cd114cea98d9326ca1c421")
],
"lists" : [
{
"list" : "1",
"cards" : [
{
"name" : "2",
"Author" : [
"59df60fb6fad6224f4f9f22d",
"59df60fb6fad6224f4f9f22d",
"59df60fb6fad6224f4f9f22e"
]
},
{
"name" : "3",
"Author" : []
}
]
},
{
"list" : "fea",
"cards" : [
{
"name" : "card",
"Author" : []
}
]
}
],
"__v" : 0 }
Router:
router.post('/add/member', function (req, res, next) {
console.log(req.body)
Board.findOneAndUpdate({ _id: req.body._id },
{
$set: {
lists : req.body.lists
}
},
{
upsert: true
},
((cards) => {
res.send(cards)
})
)
});
model:
var mongoose = require('mongoose');
var Schema = mongoose.Schema;
var BoardSchema = new Schema({
name: { type: String, maxlength: 20 },
lists : { type: Array },
users : [{ type : Schema.Types.ObjectId, ref: 'User' }],
});
module.exports = mongoose.model('Board', BoardSchema);
And here is function with adding poeple
$scope.addMemberToCard = (indexList, indexCard, member) => {
$scope.board.lists[indexList].cards[indexCard].Author.push(member);
console.log( $scope.board.lists[indexList].cards[indexCard].Author)
return ApiService.staff.addMemberToCard($scope.board).then(function () {
})
}
You could use the mongoose Types ObjectID method and then transform the string sent into an ObjectID.
const id = new new mongoose.Types.ObjectId(Author);
I'm just starting out with vue resource (and ajax in general) and I'm having trouble listing an array that's nested in my API.
If this is my sample JSON:
{
"item1" : "data",
"item2" : 1234,
"item3" : 5678,
"item6" : "data",
"item7" : [ {
"id" : 0,
"data2" : "testdata",
"data3" : "testdata",
},{
"id" : 2,
"data2" : "testdata",
"data3" : "testdata",
},{
"id" : 3,
"data2" : "testdata",
"data3" : "testdata",
} ]
}
I want to pass the item7 array through a list in my html like this:
<div id="app">
<ul v-for="item in items">
<li>{{ item.data2 }} {{ item.data3 }}</li>
</ul>
</div>
Here's my js:
window.onload = function() {
new Vue({
el: '#app',
data: {
items: {}
},
ready: function () {
this.$http.get('/api/items', function(data) {
console.log(data);
this.items = data.item7[];
});
},
});
};
Naturally this returns nothing, I'm not sure how to loop the array through this.items = data.item7[]; with vue resource.
You just need to write this.items = data.item7, no need for [].
You also need to bind this to the function. When you're in the callback from the HTTP request, this refers to something else. So you can use .bind(this) like so:
this.$http.get('/api/items', function(data) {
this.items = data.item7;
}.bind(this));
Lastly, you should instantiate items as an array if it is going to be an array:
data: {
items: []
},
In my application JSON response doesn't have any root variable ,It comes as following when i call the JSON
[
{
"itemID" : "1",
"errorMsg" : "",
"itemName" : "Car",
"itemDesc" : "Model NEW 2003",
"itemPurchased" : "N",
"itemImage" : "dsafadsf3r3rsdcvcawtr",
"response" : "Success"
},
{
"itemID" : "2",
"errorMsg" : "",
"itemName" : "Bike",
"itemDesc" : "Model NEW 2003",
"itemPurchased" : "N",
"itemImage" : "dsafadsf3r3rsdcvcawtr",
"response" : "Success"
},
{
"itemID" : "3",
"errorMsg" : "",
"itemName" : "Airplane",
"itemDesc" : "Model NEW 2003",
"itemPurchased" : "N",
"itemImage" : "dsafadsf3r3rsdcvcawtr",
"response" : "Success"
}
]
JSON Calling method
function viewgiftlist()
{
Ext.Ajax.request({
// url: App.gvars.apiurl + 'ShowItems/userID='+App.gvars.userid, // url : this.getUrl(),
url : 'http://192.168.1.155:8181/WishList/ShowItems/userID=1',
method: "GET",
useDefaultXhrHeader: false,
withCredentials: true,
success: function (response) {
//alert("Success Alert");
var respObj = Ext.JSON.decode(response.responseText);
// alert(respObj);
Ext.getCmp('myitemspnl').setData(respObj[0]);//Object specfying
Ext.Msg.alert("Success",response);
},
failure: function (response) {
var respObj = Ext.JSON.decode(response.responseText);
// alert("Failure Alert");
Ext.Msg.alert("Error",response.responseText);
}
});
}
JSON Loading Panel
tpl: new Ext.XTemplate(
'<div style="margin:0px;background:#fff;" ><table style="margin:0px;padding:0px;height:40px;" width="100%" ><tr><td style="padding:2px 5px;width:90%;"><span><img src=""/></span><span>{itemName}<br>{itemDesc}</span></td><td style="padding:2px 10px;width:10%;"><img src="resources/img/arrow.png" onclick="viewgiftdetails(\'{itemId}\',\'{itemPurchased}\',this)"/></td></tr></table></div>',
I can show the contents by given the index at respObj[0] or respObj[1]. How to show/load all contents which coming JSON response.Please help to solve
You should try like this
Ext.create('Ext.List', {
width: 320,
height: 290,
id : 'itemList',
itemTpl: ['<div style="margin:0px;background:#fff;" >'+
'<table style="margin:0px;padding:0px;height:40px;" width="100%" >'+
'<tr><td style="padding:2px 5px;width:90%;"><span><img src=""/>'+
'</span><span>{itemName}<br>{itemDesc}</span></td>'+
'<td style="padding:2px 10px;width:10%;">'+
'<img src="resources/img/arrow.png" />'+
'</td></tr></table></div>'].join(),
listeners : {
itemtap: function (list, index, item, record, senchaEvent) {
if (senchaEvent.event.target.nodeName == 'IMG') {
var data = record.getData();
var itemId = data.itemId;
var itemPurchased = data.itemPurchased;
// Call viewgiftdetails method and pass itemId and itemPurchased
}
}
}
});
In ajax request success method set data for the list
success: function (response) {
var respObj = Ext.JSON.decode(response.responseText);
Ext.getCmp('itemList').setData(respObj);
Ext.Msg.alert("Success",response);
},
I have an app in backbone where I want to find inside a Json record where hotel_id = 1 for example.
I have done in this mode:
var Room = Backbone.Model.extend();
var Rooms = Backbone.Collection.extend({
model:Room,
url : "includes/rooms.json"
});
var RoomView = Backbone.View.extend({
template: _.template($("#hotel-list-template").html()),
initialize: function(){
this.render();
},
render: function(){
this.bindRoomToHotel();
var element = this.$el;
element.html('');
// $(this.el).html(this.template({hotels: this.collection.models}));
},
bindRoomToHotel: function() {
allRooms = new Rooms();
allRooms.fetch();
rooms = allRooms.where({'hotel_id' : 1});
console.log(rooms);
}
});
I have cut many parts but the problem is inside bindRoomHotel when I make the where function return me empty.
This is my json:
[
{
"id" : "r1",
"hotel_id" : "1",
"name" : "Singola"
},
{
"id" : "r1_1",
"hotel_id" : "1",
"name" : "Doppia"
},
{
"id" : "r2",
"hotel_id" : "2",
"name" : "Singola"
},
{
"id" : "r2_1",
"hotel_id" : "2",
"name" : "Tripla"
}
]
How to find record with hotel_id=1?
Pretty sure you don't need quotes round the attribute name, maybe try this
rooms = allRooms.where({ hotel_id : 1 });
edit: I don't see where you are initializing those objects in the code you have provided, i'd expect to see something like this.
var Room = Backbone.Model.extend();
var Rooms = Backbone.Collection.extend({
model: Room,
url: "includes/rooms.json"
});
var RoomView = Backbone.View.extend({
template: _.template($("#hotel-list-template").html()),
initialize: function () {
this.render();
},
render: function () {
this.$el.html(_.template(this.template, this.collection.where({ hotel_id: 1 }));
}
});
var roomsCollection = new Rooms();
var roomView;
roomsCollection.fetch({
success: function ( rooms ) {
roomView = new RoomView( collection: rooms );
}
});