I have a problem with a "each" loop in a handlebars template:
I pass to the handlebars template one object as follows:
var data = {
blog = blogModel, // Backbone Model
user = userModel // Backbone Model
}
this.el.html(template(data.toJSON()))
This is my models structure:
blogModel
title: "myblog",
posts: [{
text: "first post",
datetime: "12/10/2010
},
{
text: "second post",
datetime: "10/10/2010
}
...
]
userModel
name: "John",
email: "john#gmail.com"
Handlebars template
{{#each blog.posts}}
<div>{{title}}</div>
...
<span>{{user.email}}</span>
{{/each}}
My problem is that I can´t output {{user.email}} because it´s in the context of {{#each blog.posts}}, it seems that only can output the blog properties.
If I put the {{user.email}} out of the loop it works
You can step up one level in the scope using ../ so something like this should work:
{{#each blog.posts}}
...
<span>{{../user.email}}</span>
{{/each}}
Related
I'm using AngularJS 1.6.4 and NeDB.
When I try to get every users in the database, NeDB return me a json file with every users.
So I try to display them with AngularJS but when I try to display them with ng-repeat="user in users" I can only display them by using {{ user[0].name }} but it's only display one user instead of every users, I would like it to work by using {{ user.name }}.
EDIT : This is how my JSON file looks like
[
{ _id: 1,
name: 'Antoine',
createdAt: 2017-04-18T06:42:18.473Z,
updatedAt: 2017-04-18T06:42:18.473Z
},
{ _id: 2,
name: 'Louise',
createdAt: 2017-04-18T06:42:18.478Z,
updatedAt: 2017-04-18T06:42:18.478Z
}
]
EDIT 2: Trying the solution of #PansulBhatt
Pansul Bhatt's solution
Seems like you want to iterate over the entire JSON so instead of considering it to be a list why don't you try to iterate it like a object ,something like :
<tr ng-repeat="(key, value) in data">
<td> {{key}} </td> <td> {{ value }} </td>
</tr>
Now you will have all the keys and all the values associated to those keys defined to you. I can help more if you could send the JSON but I think this would help.
Okay guys, first I would like to thank you very much for the answers about my question !
But I also want to apologize because it was an error from my controller.
My code was :
$scope.getAllUsers = function() {
$http.get("users").then(function(response) {
$scope.users = response;
});
}
And I resolve it with a simple modification :
$scope.getAllUsers = function() {
$http.get("users").then(function(response) {
$scope.users = response.data;
});
}
$scope.user=[
{ _id: 1,
name: 'Antoine',
createdAt: 2017-04-18T06:42:18.473Z,
updatedAt: 2017-04-18T06:42:18.473Z
},
{ _id: 2,
name: 'Louise',
createdAt: 2017-04-18T06:42:18.478Z,
updatedAt: 2017-04-18T06:42:18.478Z
}];
Your JSON is not valid as your dates should be strings. Run the following snippet (I also used a date format).
You can display it using ng-repeat as the following:
var myApp = angular.module('myApp', []);
myApp.controller('MyCtrl', ['$scope', function($scope) {
$scope.users = [{
_id: 1,
name: 'Antoine',
createdAt: '2017-04-18T06:42:18.473Z',
updatedAt: '2017-04-18T06:42:18.473Z'
}, {
_id: 2,
name: 'Louise',
createdAt: '2017-04-18T06:42:18.478Z',
updatedAt: '2017-04-18T06:42:18.478Z'
}];
}]);
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>
<div ng-app="myApp" ng-controller="MyCtrl">
<div ng-repeat="user in users">
{{user.name}} {{user.createdAt | date: 'dd/MM/yyyy'}}
</div>
</div>
JSFiddle demo
I have been trying to find the reason why my Ionic template is not displaying JSON data. I just started working and reading on ionic framework and angularjs.
please bear with my newbie questions;
1.) what is the error or cause why the json record is not displaying on the HTML?
2.) I have seen plenty of code samples where the Json codes is written on the controller.js instead on the services.js. Which one is standard and safe?
3.) I am having doubts regarding my json output, Can someone please confirm if the format is correct.
You help on this is really appreciated,. thanks in advance
here is my Console status:
Objectconfig: Objectdata: Array[1]0: Array[1]0: Array[1]0:
Objectcapacity: "7"fuelcap: "120"
make: "Nissan"model: "LoadMaster II"platenumber: "TRG0122"
vehiclecode: "TRK0004"vehicleid: "8"wheelnumber: "10"
__proto__: Objectlength: 1__proto__: Array[0]
length: 1__proto__: Array[0]length: 1__proto__: Array[0]headers: (name)status: 200statusText: "OK"__proto__: Object
On my template/HTML file:
<ion-list id="vehicleInformation-list1" class=" " ng-repeat="recs in vehiclerecord">
<ion-item id="vehicleInformation-list-item1" class=" ">Vehicle Model
<span class="item-note">{{ recs.model }}</span>
</ion-item>
</ion-list>
My Controller file:
.controller('vehicleInformationCtrl', function($scope, $http) { // TIP: Access Route Parameters for your page via $stateParams.parameterName
// var _this = this;
$http.get('http://myurlsample.com/webserve/').then(function(vehicleinfo ) {
$scope.vehiclerecord = vehicleinfo.data;
console.log(vehicleinfo);
alert(JSON.stringify(vehicleinfo));
}).catch(function(vehicleinfo)
{
console.log(vehicleinfo);
});
})
my Route.js file contains:
.state('tabsController.vehicleInformation', {
url: '/vehicleinfo',
views: {
'tab4': {
templateUrl: 'templates/vehicleInformation.html',
controller: 'vehicleInformationCtrl'
}
}
})
Via Jsonview a record look like this;
[
[
[
{
vehicleid: "8",
platenumber: "TRG0122",
make: "Nissan",
model: "LoadMaster II",
capacity: "7",
fuelcap: "120",
wheelnumber: "10",
vehiclecode: "TRK0004"
}
]
]
]
If I'm reading your jsonview output correctly, it looks like there's a lot of nesting going on:
[[[{model: "LoadMaster II", ...}]]]
The ng-repeat you have there will only work if the $scope.vehiclerecord looks like this:
[{model: "LoadMaster II", ...}, ... ]
Note that this is simply an array of objects with no nested arrays like your jsonview output.
So the solution is to play with vehicleinfo.data from the http response until you have only an array of objects. Based on the jsonview you have there, this would work:
$scope.vehiclerecord = vehicleinfo.data[0][0];
Rather new to handlbars.js but my #each is functional until I try to access a nested attribute. Specifically author.name
<!-- Handlebars.js Blog Template -->
<script id="posts-tpl" type="text/x-handlebars-template">
{{#each post}}
<div class="blog-post">
<h2 class="blog-post-title">{{title}}</h2>
<p class="blog-post-meta">{{author.name}}</p>
<div>{{{body}}}</div>
</div>
{{/each}}
</script>
Chrome Javascript console shows author as having attribute 'name' with the correct data.
The Backbone.js view appears to be working also:
var PostsView = Parse.View.extend({
template: Handlebars.compile($('#posts-tpl').html()),
render: function(){
var collection = { post: this.collection.toJSON() };
this.$el.html(this.template(collection));
}
I have a full example at http://picze.co/blog
If you take a look at what you're passing into the template, you'll see the issue.
In your render function, try inspecting what this.collection.toJSON(); actually is.
Basically, it looks something like this:
[
{
author: {
__type: "pointer",
className: "_User",
objectId: "JCAjG1AIN0"
},
title: "WTFBBQ",
body: "<p><h3>test</h3> egg on face. This cannot be good. </p>"
}
]
Looks like the author is missing the name attribute
EDIT
Seems like the name attribute exists in the model but it's nested as another model so when you call .toJSON() you won't get it.
One way would be to include the author model as well:
var collection = { post: this.collection.toJSON() };
for (var i=0; i<collection.post.length; i++) {
if (collection.post[i].author) {
collection.post[i].author = this.collection.at(i).get('author').toJSON();
}
}
I'm not familiar with parse.js so this may not be the best solution, but it should work
I'm trying to learn AngularJS (along with Ionic Framework) and have got stuck because I can't get my page to reflect new items.
I use ng-repeat to display items on a page.
I have a delete item button which works.
When I click delete, that single item disappears off the page. All good so far.
However, when I try to add/push a new item nothing happens. If I debug in chrome and inspect the TimeEntries array I can see that the item IS being added to the array, but the page doesn't update to display the new item.
I don't understand why my deleteItem works perfectly fine, but testAdd does not work
Simplified code below....
In my html I have:
<ion-list ng-controller="EntriesCtrl">
<ion-item ng-repeat="entry in model.TimeEntries">
<div class="row">
<div>{{entry.JobCode}}</div>
<div>{{entry.Description}}</div>
<div>{{entry.MinutesSpent}}</div>
</div>
<ion-option-button ng-click="deleteItem(entry, $index)">
</ion-option-button>
</ion-item>
</ion-list>
<a ng-click="testAdd()">Add New</a>
In my controller I have:
$scope.model = {
TimeEntries: [
{ Id: 1, Date: new Date(), JobCode: 'JobCode.123', Description: "Blah blah blah", TimeSpent: 15 },
{ Id: 2, Date: new Date(), JobCode: 'JobCode.1', Description: "Blah blah", TimeSpent: 25 },
{ Id: 3, Date: new Date(), JobCode: 'JobCode.12', Description: "Blah blah blah", TimeSpent: 45 },
{ Id: 4, Date: new Date(), JobCode: 'JobCode.3', Description: "Blah blah blah", TimeSpent: 115 }
]
};
$scope.testAdd = function () {
$scope.model.TimeEntries.push({ Id: 5, Date: new Date(), JobCode: 'JobCode.1', Description: "Blah blah", TimeSpent: 25 });
}
$scope.deleteItem = function (entry, index) {
$scope.model.TimeEntries.splice(index, 1);
}
Pyetras' solution is correct but I have a follow-up question.
In my app.js I define the page as using the EntriesCtrl
.state('app.timesheetDay', {
url: "/timesheet-day/{date}",
views: {
'menuContent': {
templateUrl: "templates/timesheet-day.html",
controller: 'EntriesCtrl'
}
}
})
Because I defined that page to use EntriesCtrl, I thought any function called from that page would automatically be in the correct scope?
Why wasn't testAdd() firing under the correct scope in my above example?
After fiddling around it looks like if I remove the ng-controller attribute then the original testAdd works perfectly fine, so I guess I was narrowing/breaking the scope by defining it both in my state config and in the page attribute
Your add button is outside the scope of the controller, move it inside the controller element like this:
<ion-list ng-controller="EntriesCtrl">
<ion-item ng-repeat="entry in model.TimeEntries">
<div class="row">
<div>{{entry.JobCode}}</div>
<div>{{entry.Description}}</div>
<div>{{entry.MinutesSpent}}</div>
</div>
<ion-option-button ng-click="deleteItem(entry, $index)">
</ion-option-button>
</ion-item>
<a ng-click="testAdd()">Add New</a>
</ion-list>
Hello guys im struggeling with ionic and angular i build an news site view with menu points like this
ionic menu points
i wrote my news in an array
for example
http://plnkr.co/edit/ZWOHlCmZDxUkd4laWN4t?p=catalogue
.controller('NewsCtrl', function($scope) {
var items = [
{id: 1, news_item: 'NEWS EXAMPLE'}
];
});
how can i route the right path to the news_item.html site which i klicked on. so if i click on first one i get the tempalte with 'NEWS EXAMPLE'
I couldn't test my answer because your plunker is not working. I think you forgot the index.html file.
But I believe you should add to your items list the url to redirect your page :
.controller('NewsCtrl', function($scope) {
var items = [
{id: 1, news_item: 'NEWS EXAMPLE', template_url : '/path/to/template'}
];
});
Then you can add the path to a href in your <a></a> block.
Hope it will help
Change your variable to be $scope.links this will make it available in the view for repeating using ng-repeat. You can then access values in the JSON Object as setting your href value to the template_url.
.controller('NewsCtrl',function($scope)({
$scope.links = [{
id:1,
news_item: 'NEWS EXAMPLE',
template_url: '/path/to/template'
},
{
id:2,
news_item: 'NEWS EXAMPLE',
template_url: 'path/to/tempalte'
}];
})
<div class='rows' ng-repeat="link in links">
<a href='{{link.template_url}}' class='col' value='{{link.news_item}}' />
</div>
Hope this helps