Want to check out Alloy Samples in an actual app? Look at the KitchenSink-v2 application on GitHub.
This provides a sample of how to use an Alloy Controller.
Conditional Statements in Views
One challenge that comes up from time to time is how to hide and show content in a view based on a condition within the app. For example, showing or hiding content when a view opens based on wether the user has logged in or not.
Here’s a simple example that shows a View that has two visual states — one where it shows the user is logged in and one when they’re not.
alloy.js file called
This kind of works in terms of the showing and hiding of elements, but the problem is that both views were rendered to the view when it opened, and then the visibility changed. This means that if the user isn’t logged in, there’s a big white space above the non-logged-in view.
The “classic” way of dealing with this was to not use show/hide at all but to change the heights:
This works, but it’s messy. We’re also assuming that the default setting of each view should be
Ti.UI.SIZE which isn’t ideal.
Thankfully, there’s a simple to do this with Alloy using IF attributes within the XML View.
Let’s update our View XML:
You’ll notice a couple of things — we’ve added an IF attribute to the
View element that calls a method called
alloy.js. You’ll also notice the second
View if attribute prefixes the method with ! because we want that to show if the method returns false.
When creating the View, Alloy is checking the method and if it returns true, the first view is rendered, and if false, the second view. What’s nice about this is that it only renders one or the other — so there’s no white space anymore.
Similarly, you can use IF attributes in TSS definitions to change the way elements display based on custom properties or methods, for example:
You can even use conditional queries by defining custom methods in your models in Alloy, and then render elements based on those methods when data-binding. In this example, a comment row is only displayed if a model has a method called
shouldShowCommentRow which returns
You can find out more about buy checking out our guide on Custom query styles.