Template not work with Backbone and Handlebars - json

Here I have problem to render my template with handlebars and backbone.
I don't know why my each block doesn't work.
I rewrite my template several times and my json but it never work.
If someone have an idea of where my mistake here :)
here my index.html:
<body>
<div id="page">
</div>
<script type="text/x-handlebars-template" id="template">
<h4> test template </h4>
{{#each rappers}}
<p>{{rappers.blazz}} !!!!!!</p>
{{/each}}
</script>
</body>
I got this result :
test template
!!!!!!
!!!!!!
!!!!!!
but not the {{blazz}} value ..
here my js:
var Rapper = Backbone.Model.extend({
// defaults : {
// blazz: ""
// },
initialize: function() {
console.log("Création d'un nouveau rapper");
}
})
var Rappers = Backbone.Collection.extend({
// defaults : {
// blazz: "pas de blazz"
// },
model : Rapper,
url : './js/data.json'
})
var RapperList = Backbone.View.extend({
el:'#page',
render: function(){
var that = this;
var rappers = new Rappers();
rappers.fetch({
success: function(rappers){
var source = $("#template").html();
var template = Handlebars.compile(source);
that.$el.html(template({rappers : rappers.toJSON()}));
}
})
}
});
var Router = Backbone.Router.extend({
routes:{
'' : 'home'
}
});
var rapperList = new RapperList();
var router = new Router();
router.on('route:home',function(){
rapperList.render();
})
Backbone.history.start();
And my JSON:
[
{"rapper" :
[
{"blazz" : "person1"},
{"nom" : "paul"},
]
},
{"rapper" :
[
{"blazz" : "person2"},
{"nom" : "mike"},
]
},
{"rapper" :
[
{"blazz" : "person3"},
{"nom" : "jean"},
]
}
]

Can you try this:
<body>
<div id="page">
</div>
<script type="text/x-handlebars-template" id="template">
<h4> test template </h4>
{{#each rappers}}
<p>{{blazz}} !!!!!!</p>
{{/each}}
</script>
</body>
By using directly {{blazz} and not {{rappers.blazz}

Here my solution :
I slightly change the shape of the code. (and added a few more items in).
So here the new JSON :
[
{
"blazz" : "blazz1",
"prenom" : "prenom1",
"age" : 20,
"album" :
[
{
"nom" : "album1",
"vente" : 1000}
,
{
"nom" : "album2",
"vente" : 10068
}
]
},
{
"blazz" : "blazz2",
"prenom" : "prenom2",
"age" : 15,
"album" :
[
{
"nom" : "album1",
"vente" : 1000}
,
{
"nom" : "album2",
"vente" : 108798
}
]
},
{
"blazz" : "blazz3",
"prenom" : "prenom3",
"age" : 35,
"album" :
[
{
"nom" : "album1",
"vente" : 6546
}
,
{
"nom" : "album2",
"vente" : 4816
}
]
}
]
and here the new template :
{{#each rappers}}
<p>blazz: {{blazz}} prenom: {{prenom}} nom: {{nom}}</p>
<ul>
{{#each this.album}}
<li>nom: {{nom}}</li>
{{/each}}
</ul>
{{/each}}
The difference is here :
Before :
{"object" :
[
{"foo" : "content"},
{"foo" : "content"}
]
}
And after
{"object" :
[
{"foo" : "content",
"foo" : "content"}
]
}

Related

Access nested objects in API using vue resource

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: []
},

Angular.js table mapping brain fahrt

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. :-)

Populate data in DropDown box using sapui5

var oItemsData = {
items: [
{"key" : "City1", "text" : "India"},
{"key" : "City2", "text" : "America"},
{"key" : "City3", "text" : "Germany"},
{"key" : "City4", "text" : "France"}
]
};
var oItemsModel = new sap.ui.model.json.JSONModel(oItemsData);
sap.ui.getCore().setModel(oItemsModel, "items");
new sap.ui.commons.Label({text:"FirstOne"}),
new sap.ui.commons.DropdownBox({value:"",required: true,
items: {
path: "items>/items",
template: new sap.ui.core.ListItem({
text: { path: "items>text" }//how to filter
})
}
}),
new sap.ui.commons.Label({text:"SecondOne"}),
new sap.ui.commons.DropdownBox({value:"",required: true,
items: {
//populate on the basis of 1st one's input
})
}
})
This is working fine with the above json data.
But I faced problem when my json data looks like below :
{
"CountryList" : [
{
"key" : "City1", "text" : "India"
}, {
"key" : "City2", "text" : "America"
}, {
"key" : "City3", "text" : "Germany"
}, {
"key" : "City4", "text" : "France"
}
]
}
I attempted this below code :
var oItemsModel = new sap.ui.model.json.JSONModel();
oItemsModel.loadData("json/countryList.json");
sap.ui.getCore().setModel(oItemsModel, "CountryList");
new sap.ui.commons.DropdownBox("Cities", {
selectedItemId : "{CountryList>/CountryList/0/callingfrom}",
items: {
path: "items>/CountryList",
template: new sap.ui.core.ListItem({
key: {path: "items>key"},
text: {path: "items>text"}
})
},
})
But not working.
How to build data in dropdown box when Json format like above.
i am guessing here but all you have done is change the aggregation name from "items" to "CountryList"
therefore try referencing the new name
new sap.ui.commons.DropdownBox({value:"",required: true,
items: {
path: "items>/CountryList", // >> here
template: new sap.ui.core.ListItem({
text: { path: "items>text" }//how to filter
})
}
}),
Solution of the above problem :
var oItemsModel = new sap.ui.model.json.JSONModel();
oItemsModel.loadData("json/countryList.json");
sap.ui.getCore().setModel(oItemsModel, "CountryList");
new sap.ui.commons.DropdownBox("Cities", {
selectedItemId : "{CountryList>/CountryList/0/callingfrom}",
items: {
path: "CountryList>/CountryList",
template: new sap.ui.core.ListItem({
key: {path: "CountryList>key"},
text: {path: "CountryList>text"}
})
},
})

retrieve an element from a json list with angularjs

I have this list JSON:
[{
"password" : "ppp",
"function" : 0,
"id" : 1,
"login" : "ness",
"nom" : "nesrine",
"mail" : "nes#gmail",
"tel" : "238555555"
},
{
"password" : "pass",
"function" : 0,
"id" : 2,
"login" : "bilel.troudi",
"nom" : "bilel",
"mail" : "bilel.troudi91#gmail",
"tel" : null
},
{
"password" : "undefined",
"function" : 1,
"id" : 4,
"login" : "undefined",
"nom" : "ahmed",
"mail" : "ahmed#gmail.com",
"tel" : "221474"
},
{
"password" : "khm",
"function" : 0,
"id" : 5,
"login" : "khm",
"nom" : "khmayes",
"mail" : "bke#live.fr",
"tel" : "235684522"
}
]
I want to retrieve the names(nom) of users with angular I recovered this list in a variable in my code.
if you do not want to use angular js then you can use simple jquery too.
var list = [{"password":"ppp","function":0,"id":1,"login":"ness","nom":"nesrine","mail":"nes#gmail","tel":"238555555"},{"password":"pass","function":0,"id":2,"login":"bilel.troudi","nom":"bilel","mail":"bilel.troudi91#gmail","tel":null},{"password":"undefined","function":1,"id":4,"login":"undefined","nom":"ahmed","mail":"ahmed#gmail.com","tel":"221474"},{"password":"khm","function":0,"id":5,"login":"khm","nom":"khmayes","mail":"bke#live.fr","tel":"235684522"}];
var nameList = [];
for(var i=0;i<list.length;i++){
nameList.push(list[i].nom);
}
$scope.list =[{"password":"ppp","function":0,"id":1,"login":"ness","nom":"nesrine","mail":"nes#gmail","tel":"238555555"},{"password":"pass","function":0,"id":2,"login":"bilel.troudi","nom":"bilel","mail":"bilel.troudi91#gmail","tel":null},{"password":"undefined","function":1,"id":4,"login":"undefined","nom":"ahmed","mail":"ahmed#gmail.com","tel":"221474"},{"password":"khm","function":0,"id":5,"login":"khm","nom":"khmayes","mail":"bke#live.fr","tel":"235684522"}];
$scope.nameList = [];
angular.forEach($scope.list,function(Obj,val){
$scope.nameList.push(Obj.nom);
});
you can use this code. in $scope.nameList you can get all names.
For this code you have to use angular js
Try
function getNames() {
return $http.get("/allU").then(function(result) {
return result.data.map(function(item) {
return item.nom;
});
});
}
getNames().then(function(data) {
$scope.names = data; //$scope.names = ["nesrine", "bilel", "ahmed", "khmayes"]
})

How to select an item from json data with ngResource?

I'm trying to select data from my json file with
$resource request :
Im using a global variable productSelected in my controller,
but when I change it's value with ng-model , that don't do an effect on the model and the value of reference still the same!
Anyone have an idea please ?
Here is my code :
var myApp = angular.module('myApp', ['ngResource']);
myApp.factory('Produits',['$resource', function ($resource) {
return $resource('data/produits.json/:id',{id: "#id"},
{
'get': {method:'GET'},
'save': {method:'POST'},
'query': {method:'GET', isArray:true},
'remove': {method:'DELETE'},
'delete': {method:'DELETE'}
}
);
}]);
myApp.controller('produitsCtrl', function($scope, $http,Produits,$log) {
$scope.productSelected=0;
Produits.query(function(data){
$scope.produits=data;
$scope.reference=$scope.produits[$scope.productSelected].reference ;
});
});
<div ng-app="myApp" >
<div ng-controller="produitsCtrl">
Product : <input type="text" ng-model="productSelected"/> {{ productSelected }} <br/>
Reference : {{reference}}
</div>
</div>
produits.json
[{
"id" : 1,
"reference": "AA"
},
{
"id" : 2,
"reference": "BB"
}]
Just have a look at this code may be helpful for you
<body ng-app="myApp" data-ng-controller="MainCtrl" id="div1">
Product : <input type="text" ng-model="productSelected" ng-change="fun(productSelected)"/> {{ productSelected }} <br/>
Reference :<p ng-model="reference"> {{reference}} </p>
<script>
var app = angular.module('myApp', []);
app.controller('MainCtrl', function($scope){
$scope.productSelected=0;
$scope.produits= [{
"id" : 1,
"reference": "AA"
},
{
"id" : 2,
"reference": "BB"
}];
$scope.reference=$scope.produits[$scope.productSelected].reference;
$scope.fun=function(val){
//alert(val)
if(val!=undefined && val!=null && val!='')
$scope.reference=$scope.produits[$scope.productSelected].reference;
else
$scope.reference=$scope.produits[0].reference;
};
});
</script>
</body>