each with index and modulo in ember and handlebar - loops

I'm creating a slide - so there's 3 images every one div like so
<div>
<img />
<img />
<img />
</div>
</div>
<img />
<img />
<img />
</div>
None of the code around the internet works flawlessly -
https://github.com/johanpoirier/resthub-backbone-stack/commit/8a318477d56c370d2a0af4da6eae9999c7bb29da
http://jaketrent.com/post/every-nth-item-in-handlebars-loop/
http://rockycode.com/blog/handlebars-loop-index/
http://www.arlocarreon.com/blog/javascript/handlebars-js-everyother-helper/
and yes including the answers here in stack overflow.
Can anyone provide some code that works perfectly at this current period (version of Ember/Handlebar)?
I have an array of models so i'd like to do something like
{{#each model}}
{{if index % 3 == 0}}
{{/if}}
{{/each}}

I have been finding that index or #index do not work from within the template, but you can access it from within a helper.
I've made an example here that demonstrates this:
http://jsbin.com/egoyay/1/edit
Edit: Adding code to answer, demonstrating {{else}} block
Handlebars helper (for non-Ember use):
Handlebars.registerHelper('ifIsNthItem', function(options) {
var index = options.data.index + 1,
nth = options.hash.nth;
if (index % nth === 0)
return options.fn(this);
else
return options.inverse(this);
});
Usage:
<ol>
{{#each model}}
<li>
{{#ifIsNthItem nth=3}}
Index is a multiple of 3
{{else}}
Index is NOT a multiple of 3
{{/ifIsNthItem}}
</li>
{{/each}}
</ol>

If you specify itemViewClass in each helper, then it will create a view for each item and set contentIndex property:
{{#each model itemViewClass="Ember.View"}}
{{view.contentIndex}}
{{/each}}
tested in Ember v1.1.0

Related

How to use lang var inside handlebars loop array?

I have codeigniter project with handlebars.js
and I have page (page.template.html) through codeigniter api I pass lang variables
inside the page when loop with handlebars with an array I can't use the lang var because it will get form the array
is there anything to escape getting from the array .. OR any other solutions?
in the code below .. the array is (orgLang) and (this) is the element
the array looks like:
orgLang = ['ar' ,'en']
and the lang var is (details.slug)
{{#each orgLang}}
<a class="dropdown-item lang-picker-item" href="{{details.slug}}/{{this}}">
<img width="25px" src="assets/images/flags/{{this}}.jpg" >
</a>
{{/each}}
I found this solution and it's worked
add ../ before the variable
because it's in another scope
{{#each orgLang}}
<a class="dropdown-item lang-picker-item" href="{{../details.slug}}/{{this}}">
<img width="25px" src="assets/images/flags/{{this}}.jpg" >
</a>
{{/each}}

Geting incorrect $index value for parent ng-repeat loop

I have following code and try to use $index in delete function but it gives incorrect value of it.
<li ng-repeat="joinMember in data.teamMember | orderBy:'member.screenName || member.fname' ">
<div class="member-list-img">
<a ng-href="">
<img ng-src="{{joinMember.member.data.image ? (joinMember.member.data.imageType == 'avatar' ? '/public/images/avatars/' + joinMember.member.data.image : '/public/images/' + joinMember.member.data.image) : '/public/images/avatars/avatar-73.png'}}" width="100%" alt="{{joinMember.member.screenName ? joinMember.member.screenName : joinMember.member.fname + ' ' + joinMember.member.lname }}" />
</a>
</div>
<div class="member-list-cont">
<h4>
<a ng-href="#">
{{joinMember.member.screenName ? joinMember.member.screenName : joinMember.member.fname + ' ' + joinMember.member.lname }}
</a>
</h4>
<span>{{joinMember.created | date : "MMMM d, y"}}</span>
</div>
<div ng-if="data.canModify" class="membr-delete">
<a ng-href="">
<i class="fa fa-trash text_link" aria-hidden="true" ng-click="deleteTeamMember($parent.$index, joinMember.id)"></i>
</a>
</div>
</li>
That's because the directive ng-if creates a new scope for itself, when you refer to $parent, it access the immediate $parent's scope, i.e., the inner repeat expression's scope.
So if you want to achieve something you wanted like in the former, you may use this:
<div ng-repeat="i in list">
<div ng-repeat="j in list2">
<div ng-if="1">
({{$parent.$parent.$index}} {{$parent.$index}})
</div>
</div>
</div>
if you have more than one inner directives, you can use ng-init for storing $index in a variable for references in child scopes.
<div ng-repeat="i in list" ng-init="outerIndex=$index">
<div ng-repeat="j in list2" ng-init="innerIndex=$index">
<div ng-if="1">
({{outerIndex}} {{innerIndex}})
</div>
</div>
</div>
So try $parent.$parent.$index in your example and please check understanding the scopes
You are using $parent.$index in a div that have ng-if tag. which delete dom element(div) if condition is fall so that case you will receive incorrect $index value. but with ng-show it only add hide class to that div.
So try to ng-show if it is not important to remove div element instead just hide it.
Note:- You are also using orderBy filter in ng-repeat which will sort in only your DOM so if you will find incorrect object value in your controller.
As you can see in the official documentation of angularjs you should get a zero-based index via $index within a ng-repeat. Try the example by angularjs here. Try to debug data.teamMember in your controller to make sure that this is the correct array you'd like to iterate.

ng-repeat - content to show if array is empty or null

I've a deep nested ng-repeat lists, and only in the last loop I've to display alternate content if list was empty. I'm new to angular, saw some posts online please help me where can I use content if list is empty. The ng-repeat=sessions in day could be empty.
<ul class="day">
<li ng-repeat="sessions in day">
<ul class="table-view">
<li class="table-view-cell" ng-repeat="(heading, session) in sessions">
<span class="group">{{heading}}</span>
<ul class="cell">
<li class="cell-content" ng-repeat="val in session" ng-click="getSession(val.id)">
<div class="time" style="background-color:#{{val.color}}">
<span>{{val.start | date:"h:mma"}}</span>
<span>to</span>
<span>{{val.end | date:"h:mma"}}</span>
</div>
<div class="session" ng-class-odd="'odd'" ng-class-even="'even'">
<span class="name">{{val.name}}</span>
<span class="room">Room: {{val.room}}</span>
</div>
</li>
</ul>
</li>
</ul>
</li>
</ul>
1). CSS approach. I usually use pure CSS approach in such cases. With this markup (stripped extra-html):
<ul class="day">
<li ng-repeat="sessions in day">
...
</li>
<li class="no-sessions">
No sessions on this day.
</li>
</ul>
and CSS rules to hide .no-sessions li by default and make it visible only if there are no previous li tags:
li.no-sessions {
display: block;
}
li + li.no-sessions {
display: none;
}
So when sessions array is empty, there will be no li rendered and only no-sessions one will be visible. And if will hide as soon as there is at least one session on this day.
Demo: http://plnkr.co/edit/KqM9hfgTTiPlkdmEevDv?p=preview
2). ngIf approach. Of course you can use ngIf/ngShow directives for show no-records element when sessions array is empty:
<li ng-if="!day.length">
No sessions on this day.
</li>
I think this would work for your case:
<li ng-hide="day.length > 0">
No sessions on this day.
</li>
No extra CSS needed. Assumes day is an array.
http://plnkr.co/edit/WgDviOKjHKS1Vt5A5qrW
I would recommend handling that in your controller. Keeping your logic in the controller and javasript makes debugging easier and more manageable. I can think of 2 approaches: using ng-show/ng-hide or a condition for your day variable when its empty.
Option 1
ng-show/ng-hide approach:
$scope.isDayEmpty = function(){
return $scope.day.length > 0 ? false : true;
}
html:
<ul class="day">
<li ng-repeat="sessions in day" ng-hide="isDayEmpty">
...
</li>
<li ng-show="isDayEmpty">
No Sessions this Day
</li>
</ul>
Option 2:
ng-repeat approach
if($scope.day.length == 0){
$scope.day.push("No Sessions this Day");
}
This should get you essentially the same result. The first approach would make your CSS styling easier assuming you want to do something different in that case.
The second approach can vary in style depending on your code but thats an example of how you can do it. I don't know your javascript so I can't be more specific to your scenario.

Two ng-repeat, one affect another

Today I faced a strange problem for me in AngularJS.
In this example I have two ng-repeat in product (two or three images and the same number of colors) and one ng-repeat for pagination (irrelevant in this case I assume).
HTML:
<div class="item-wrapper" ng-repeat="item in pagedItems[currentPage]">
<div class="item">
<!-- Item image -->
<div class="item-image">
<ul>
<li ng-repeat="desc in item._source.description" ng-show="$first">
<img class="preview" ng-src="server/{{desc.smallImage.url}}">
</li>
</ul>
</div>
<!-- Item details -->
<div class="item-details">
<div class="product-colors">
<ul class="btn-group pull-right">
<li ng-repeat="color in item._source.description">
<img class="color" ng-src="server/{{color.thumbnailImage.url}}" />
</li>
</ul>
</div>
</div>
</div>
All I wanted to do is that click on one of colors (img.color) changes corresponding img.preview visibility. In my attempts I was always able to changed every img.preview in whole list, not the one I clicked on.
MY ATTEMPTS:
HTML
<li ng-repeat="desc in item._source.description" ng-show="$index === selectedColor">
<li ng-repeat="color in item._source.description" ng-click="changeColor($index)">
JS (controller)
$scope.changeColor = function(idx) {
$scope.selectedColor = idx || 0; //default show always first img.preview from list
};
MY ATTEMPTS #2 (working)
HTML
<li><img class="preview" ng-src="server/{{desc[__selected === $index ? __num : 0].smallImage.url}}">
<li ng-repeat="color in item._source.description" ng-click="changeColor($index, key)">
JS (controller)
$scope.changeColor = function(idx, key) {
$scope.__selected = key;
$scope.__num = idx;
};
This might be quite simple:
Considering desc and color will be referring to same object as they are of the same source.
So, desc and color should be identical and setting a property on either of them supposed to reflect on the other.
Make the changes as follow and try, havent tested though:
<li ng-repeat="desc in item._source.description" ng-show="item.__selected ? desc==item.__selected : $first">
and
<li ng-repeat="color in item._source.description">
<img class="color" ng-src="server/{{color.thumbnailImage.url}}" ng-click="item.__selected = color" />
</li>

Angularjs - How to keep count of total iterations across nested ng-repeat in the template

I have a fairly large object that needs to be iterated over in nested ng-repeat loops
A simplified version looks like this:
{{totalEvents = 0}}
<div ng-repeat="(mainIndex, eventgroup) in EventsListings">
<ul>
<li ng-repeat="event in eventgroup.events" ng-click="Current(totalEvents)">
<div class="event-item-container" ng-show="eventDetailsView[totalEvents]">
{{totalEvents = totalEvents + 1}}
</div>
</li>
</ul>
</div>
{{totalEvents = 0}
How can I keep track of totalEvents counter value.. How can I get a total number of iterations across nested loops IN the template?
you can reach many value just using $index property of ng-repeat...
HTML
<div ng-repeat="eventgroup in EventsListings" ng-init="outerIndex = $index">
<ul>
<li ng-repeat="event in eventgroup.events" ng-click="Current(totalEvents)">
<div class="event-item-container">
{{event.name}} can have unique value like
<br/>(outerIndex) * (eventgroup.events.length) + innerIndex
<br/>Total Events = {{outerIndex * eventgroup.events.length + $index}}
<br/>Inner Events = {{$index}}
</div>
</li>
</ul>
</div>
here is working PLUNKER
UPDATE
After some times and some comments I realized that my code is not calculating total iterations correctly, so I made some changes to fix it.
First mistake I made somehow I thought event numbers will be equals for every set, second one if there are more than 2 sets again it fails.
So for keeping track of total iterations I set an array which is called totalIterations in code. In this array I set total number events we already iterate so far,
For example at the finish of first set it will be length of first event group and for second it will be first and second group, and so on... For achieving this I used ng-repeat-end directive here is the final code
<div ng-repeat="eventgroup in EventsListings" ng-init="outerIndex = $index">
<ul>
<li ng-repeat="event in eventgroup.events">
<div class="event-item-container">
{{event.name}} can have unique value like
<br/>Total Events Count = {{totalIterations[outerIndex- 1] + $index}}
<br/>Innder Events = {{$index}}
</div>
<button class="btn btn-success" ng-click="Current({{totalIterations[outerIndex- 1] + $index}})">Current Event</button>
</li>
<span ng-repeat-end ng-init="totalIterations[outerIndex] = totalIterations[outerIndex - 1] + eventgroup.events.length"></span>
</ul>
</div>
and here is latest PLUNKER
I want to suggest different way to approach this, I think it's pretty cool and easy :
In the template :
<ul>
<div ng-repeat="group in obj.objectGroups">
<li>{{group.name}}</li>
<li ng-repeat="item in group.items" ng-init="number = countInit()">
Total = {{number + 1}}
</li>
</div>
</ul>
In the controller :
$scope.totalCount = 0;
$scope.countInit = function() {
return $scope.totalCount++;
}
If you really want the template to drive this calculation, you could keep a counter in the Controller and create a function that increments that counter. Then call that function from the template.
Honestly, though, it seems very strange to put this sort of logic in the view. It would make much more sense just to do a recursive count in pure Javascript in the Controller.

Resources