Mustache - How to detect array is not empty? - arrays

I want to implement the following logic with Mustache:
{{#if users.length > 0}}
<ul>
{{#users}}
<li>{{.}}</li>
{{/users}}
</ul>
{{/if}}
// eg. data = { users: ['Tom', 'Jerry'] }
Should I modify the users structure to meet the need? For example:
{{#hasUsers}}
<ul>
{{#users}}
<li>{{.}}</li>
{{/users}}
</ul>
{{/hasUsers}}
// eg. data = { hasUsers: true, users: ['Tom', 'Jerry'] }

Sorry, this may be too late. But I had similar requirement and found a better way to do this:
{{#users.length}}
<ul>
{{#users}}
<li>{{.}}</li>
{{/users}}
</ul>
{{/users.length}}
{{^users.length}}
<p>No Users</p>
{{/users.length}}
Working sample here: http://jsfiddle.net/eSvdb/

Using {{#users.length}} works great if you want the inner statement to repeat for every element of the array, but if you only want a statement to only run once, you can use:
{{#users.0}}
...
{{/users.0}}
{{^users.0}}
...
{{/users.0}}

I'm using chevron for Python. Since {{#users.length}} is implementation-dependent as described in previous answers, and doesn't work for me in Chevron, I return an object in my code which only contains the list if the list is non-empty. Presumably this technique would work for other languages too.
users = ["user1", "user2", "userN"]
user_obj = {"user_list": users} if len(users) > 0 else {}
template = """
{{#users}}
<ul>
{{#user_list}}
<li>{{.}}</li>
{{/user_list}}
</ul>
{{/users}}
"""
chevron.render(template, {"users": user_obj})

Related

ng-class not working with ng-repeat

I have a situation where I have to add class according to the condition and the ng-class is working according to it even the condition in the ng-class is true.
<ul id="" class="clowd_wall" dnd-list="vm.cardData[columns.id].data"
dnd-drop="vm.callback(item,{targetList: vm.cardData[columns.id].data, targetIndex: index, event: event,item:item,type:'folder',eventType:'sort','root':'folder',current_parent:'folder'})" ng-model="vm.cardData[columns.id].data">
<div class="emptyCol" ng-if="vm.cardData[columns.id].data.length==0">Empty</div>
<li class="dndPlaceholder"></li>
<li class="cont____item" ng-repeat="card in vm.cardData[columns.id].data | orderBy:vm.sort" dnd-draggable="card"
dnd-effect-allowed="move"
dnd-allowed-types="card.allowType"
dnd-moved="vm.cardData[columns.id].data.splice($index, 1)"
dnd-selected="vm.tree.selected = card" ng-class="{emptyCard:card.data.length==0,zoomin:vm.zoomin=='zoomin',emptyCard:!card.data}">
<div class="item" style="height:79%">
<ng-include ng-init = "root = columns.id" src="'app/partials/card.html'"></ng-include>
</div>
</li>
</ul>
ng-class="{'emptyCard': (!card.data || !vm.cardData[columns.id].data.length),'zoomin':(vm.zoomin=='zoomin')}">
Seems like you want to use vm.cardData[columns.id].data.length instead of card.data.length
Your question is not clear as don't know what card.data will contain and ".data" will be present for each iteration
If it is array then this will work "card.data.length" and if there is no "data" key in "card" then ".length" will through error i.e. if card.data itself undefined then it will not have "length" property.
Try to add condition in ng-class one by one then you will be able to figure out which condition is causing problem.
Made some small change
ng-class="{emptyCard: card.data.length==0 || !card.data,zoomin: vm.zoomin=='zoomin'}"
If you have multiple expression, try old fashioned, if it looks best:
Controller:
$scope.getcardClass = function (objCard, strZoomin) {
if (!card.data) {
return 'emptyCard';
} else if (strZoomin =='zoomin') {
return 'zoomin';
} else if (card.data.length == 0) {
return 'emptyCard';
}
};
HTML:
ng-class="vm.getcardClass(card, vm.zoomin)"
NOTE: Replace vm with your controller object.

Replace values from json

I display data from a json.
I want replace values from an other (for translation).
It's like :
<li ng-repeat="childrens in data.children track by $index">
<a>{{childrens.type}}</a>
</li>
In 'type' I can have "QUOTE", "BILL" or "DEPOSIT"...
And I want replace this value with the translation.
But I'm beginner in angular, and i work on json for the first time as well, what's the better way to do this ?
I tried to use the fonction replace() in my controller but that doesnt work :
if($scope.children.type =='QUOTE'){
$scope.children.type = $scope.children.type.replace('Facture');
}
Thanks for your help guys :)
You can do this:
<li ng-repeat="childrens in data.children track by $index">
<a>{{mapObject[childrens.type].text}}</a>
</li>
In Controller you can use javascript map
$scope.mapObject = {
"QUOTE":{
"text":"Facture"
}
}

"ng-group" feature exists on ng-repeat?

Using non-3rd party plugins:
I have an array like this:
[
{groupName:'General', label:'Automatic Updates', type:'select', values:{0:'On', 1:'Off'}},
{groupName:'General', label:'Restore Defaults', type:'button', values:['Restore']},
{groupName:'General', label:'Export & Import', type:'button', values:['Export', 'Import']},
{groupName:'Timing', label:'Double Click Speed', type:'text'},
{groupName:'Timing', label:'Hold Duration', type:'text'}
]
I want to ng-repeat over this but create groups.
The final result I'm hoping will look like this:
So basically that is a ng-repeat on the groupName to make two div containers, then it ng-repeats for each item within to add the rows.
Is this possible without having to change my array into an object like this:
[
'General': [...],
'Timing': [...]
]
If you want to do something like this, one solution is to split up the repeat into 2 separate repeats. the easiest is to do that by creating a small helper filet that filters out the unique properties. a filter like this would do:
function uniqueFilter() {
return function(arr,property) {
if (Object.prototype.toString.call( arr ) !== '[object Array]') {
return arr;
}
if (typeof property !=='string') {
throw new Error('need a property to check for')
}
return Object.keys(arr.reduce(isUn,{}));
function isUn(obj,item) {
obj[item[property]] = true;
return obj;
}
}
}
That filter will return an array that consist of the unique values of the property you want to group by.
Once you have this you can nest a couple of ngRepeats like this:
<div ng-repeat="group in vm.data| uniqueFilter:'groupName'">
{{group}}
<ul>
<li ng-repeat="item in vm.data| filter:{groupName:group}">{{item.label}}</li>
</ul>
</div>
And you should be set.
There is no need to pull in a 3rth party for this.
see it in action in this plunk.

ng-repeat doesn't seem to be working

I am trying to pull all items from my array called 'collections'. When I input the call in my html I see only the complete code for the first item in the array on my page. I am trying to only pull in the 'edm.preview' which is the image of the item. I am using Angular Firebase and an api called Europeana. My app allows the user to search and pick which images they like and save them to that specific user.
here is the js:
$scope.users = fbutil.syncArray('users');
$scope.users.currentUser.collections = fbutil.syncArray('collections');
$scope.addSomething = function (something) {
var ref = fbutil.ref('users');
ref.child($rootScope.currentUser.uid).child('collections').push(something);
}
$scope.addSomething = function(item) {
if( newColItem ) {
// push a message to the end of the array
$scope.collections.$add(newColItem)
// display any errors
.catch(alert);
}
};
and the html:
<ul id="collections" ng-repeat="item in collections">
<li ng-repeat="item in collections">{{item.edmPreview}}</li>
</ul>
First, remove the outer ng-repeat. You want to only add the ng-repeat directive to the element which is being repeated, in this case <li>.
Second, from your AngularJS code, it looks like you want to loop over users.currentUser.collections and not just collections:
<ul id="collections">
<li ng-repeat="item in users.currentUser.collections">{{item.edmPreview}}</li>
</ul>
And third, you're defining the function $scope.addSomething twice in your JavaScript code. Right now, the second function definition (which, incidentally, should be changed to update $scope.users.currentUser.collections as well) will completely replace the first.

Observing nested properties in Ember controller

I'm in the middle of a small project involving Ember. It's my very first time at working with this framework and it has not been an easy learning so far :(
Right now I'm having troubles dealing with nested arrays. What I want to do is pretty standard (at least it seems that way): I have items, item categories and category types (just a way to organize them).
The idea is that there are checkboxes (categories) that allow me to filter the items that are shown in the webpage. On the other hand, there are checkboxes (types) that allow me to check multiple catgories at a time.
In order to implement this I've defined a route (in which I retrieve all the data from these models) and a controller. Originally, I only had items and categories. In this context, I observe the changes in the filters (categories) like this: categories.#each.isChecked and then show the item selection. Unfortunately, now that the hierarchy is types->categories, is not possible to observe changes in categories in the same manner according to the docs:
Note that #each only works one level deep. You cannot use nested forms like todos.#each.owner.name or todos.#each.owner.#each.name.
I google a little bit but didn't find too much about it, so I right now I was thinking in using a custom view for categories (one that extends the Ember.Checkbox) and send an event to the controller whenever a category is checked or unchecked. Is more of a "manual" work and I guess is far from Ember's way of dealing with this type of things.
Is there a standard way of doing this?
Thanks in advance for any help.
One way of solving this would be to observe the category types and filter categories, the same way that the categories are being observed.
This is an example,
http://emberjs.jsbin.com/naqebijebapa/1/edit
(one to many relationships have been assumed)
hbs
<script type="text/x-handlebars" data-template-name="index">
<ul>
{{#each catType in catTypes}}
<li>{{input type="checkbox" checked=catType.isSelected }}{{catType.id}} - {{catType.name}}</li>
{{/each}}
</ul>
<hr/>
<ul>
{{#each cat in filteredCats}}
<li>{{input type="checkbox" checked=cat.isSelected }}{{cat.id}} - {{cat.name}}</li>
{{/each}}
</ul>
<hr/>
<ul>
{{#each item in filteredItems}}
<li>{{item.id}} - {{item.name}}</li>
{{/each}}
</ul>
</script>
js
App = Ember.Application.create();
App.Router.map(function() {
// put your routes here
});
App.CategoryType = Em.Object.extend({
id:null,
name:null,
isSelected:true
});
App.Category = Em.Object.extend({
id:null,
name:null,
type:null,
isSelected:false
});
var catTypeData = [
App.CategoryType.create({id:1,name:"type1"}),
App.CategoryType.create({id:2,name:"type2"}),
App.CategoryType.create({id:3,name:"type3"}),
App.CategoryType.create({id:4,name:"type4"})
];
var catData = [
App.Category.create({id:1,name:"cat1",type:catTypeData[1]}),
App.Category.create({id:2,name:"cat2",type:catTypeData[2]}),
App.Category.create({id:3,name:"cat3",type:catTypeData[0]})
];
var itemsData = [
{id:1,name:"item1",cat:catData[0]},
{id:2,name:"item2",cat:catData[0]},
{id:3,name:"item3",cat:catData[1]}
];
App.IndexRoute = Ember.Route.extend({
model: function() {
return Em.RSVP.hash({catTypes:catTypeData,cats:catData,items:itemsData});
}
});
App.IndexController = Ember.ObjectController.extend({
filteredItems:[],
filterItemsBasedOnCategory:function(){
var selectedCats = this.get("cats").filterBy("isSelected");
if(!Em.isEmpty(selectedCats))
this.set("filteredItems",this.get("items").filter(function(item){
return selectedCats.contains(item.cat);}));
else
this.set("filteredItems",[]);
}.observes("cats.#each.isSelected"),
filterCatsBasedOnCategoryType:function(){
var selectedCatTypes = this.get("catTypes").filterBy("isSelected");
if(!Em.isEmpty(selectedCatTypes))
this.set("filteredCats",this.get("cats").filter(function(cat){
var itContainsIt = selectedCatTypes.contains(cat.type);
if(!itContainsIt){
cat.set("isSelected",false);
}
return itContainsIt;
}));
else
this.set("filteredCats",[]);
}.observes("catTypes.#each.isSelected")
});

Resources