Angular.js Show and simplicity

(Originally posted August 22, 2013)

When mapping Streakflow to a mobile app, I decided to use Trigger.io and their forge toolchain. Considering I’ve never done mobile development, and that I wanted to deploy on ios and Andriod out of the box, and there have been many successful apps using Trigger.io, it felt like a great fit. In doing this, it meant that I needed to learn a javascript mvc framework. There were a few choices, but because I’ve been hearing so much buzz about Angular.js, and it turned out to be a great decision.

Among other niceties, Angular’s ng-show directive is particularly simple to work with. In the app, I’ve been using it as a makeshift if statement in the templates, though it turns out to work nicer. I’ll go through two different way’s I’ve used ng-show in the app.

The first example is the simplest, and will show how easy ng-show is. As a side note, I didn’t think this method would work when I saw the example online.

<div ng-show="var_in_scope">
  <h1>Variable is true!</h1>
</div>

When this variable changes in your controller, either

//h1 will be visible
$scope.var_in_scope = true;
//h1 invisible
$scope.var_in_scope = false;

The div in the html will flash off and on. That’s all there is to it. Note that the variable in the html does not need the brackets since it is in a angular directive.

The other way I’ve used ng show is by calling a function. The syntax is exactly the same, but it just calls the function from the directive.

<div ng-show="var_in_scope()">
  <h1>Variable is true!</h1>
</div>

and the javascript this time is

$scope.var_in_scope = function() {
  var random = Math.random();
  if (random > 0.5) return true;
  else return false;
}

Since ng-show evaluates the expression, and if it comes back “truthy” show the html, this works as well. Very simple and clear to anyone reading the code.

Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s