AngularJS – Directives

Directives are AngularJS system to attach behavior to DOM elements. Directives most commonly appear as attributes, but can also be tag names.

AngularJS has a set of built in Directives, and allows you to create your own.

Define a Directive with:

var app = angular.module( ‘AppName’, [] );
app.directive( ‘name’ function(){
return { /* Object Describing the Directive. */ };
} );

Native or HTML5?

Native or HTML5?

Starting a new project, you’re likely to explore what would be the correct platform as a first step. Javascript has a lot of buzz right now. There seems to be a movement to do everything in the Javascript language. At the moment you can Write your app with JS, script your server with Node.js, query your data base in JS with MongoDB. Wow, sounds like you can do it all in JS! This neat but I feel it’s important to not lose sight of the forest through the trees. In any project it’s really about choosing the right tool for the job, always.

If we’re doing everything in JS does that mean the browser is the new OS? I don’t think so. There’s a bit of the emperors new clothes in this type of thinking. The thing about JS and apps in the browser is they just don’t live up the promise. JS has a lot of hiccups and performance issues. Writing a program across HTML, CSS, and JS has a lack of elegance, and feels crude and verbose at times. Just because you can do something doesn’t mean you should. Again it’s about choosing the right tool. The big draw of JS for everything is that it leverages a common toolset, on a common platform. This can save time and money which is good, but if you are making an inferior product is it worth it?

I don’t want to sound like I have some axe to grind. I’ve had a lot of fun with JS, and if it’s the right tool for the job I’m more than happy to use it. My point is HTML5 has so much hype people are treating it like it can do no wrong, like its the wunderkind that can do anything. I just want to get real here. JS can do anything, and I suppose that’s a really a great thing. But, just like people, JS is good at somethings and not good at other things. I’m a firm believer that anyone can do anything if they put their mind to it, I’m not saying that everyone can break world records.

There’s a lot to like about writing code in one place using a common set of tools and deploying to every platform. But if the app provides weak and compromised user experience do you want to put your name on it? Look at Facebook. They had a HTML5 app, and the user experience and performance was weak. The way I see it, they essentially shoehorned a web site into an “app” and used HTML5 as their tool. They obviously bought into the promise of HTML5.

“The biggest mistake we’ve made as a company was betting on HTML5 over native”

M Zuckerberg

It’s fun to think you can recreate all of the nifty transitions and animation of a native app with JS in a browser. But, you’re not really doing your job unless you apply a critical eye and are willing to say that something is falling short of expectation. Kudos to Facebook for owning up to a problem that was theirs.

Is the browser the new OS? Computers are getting faster, and JS can do more in the browser than ever before. But I don’t think this makes JS the be all end all. There will always be something you can do native that will out of reach from the browser. Either for security, performance or other reasons. The world may spend more time in a browser than all other apps combined but, I don’t want to edit images in Safari, and I don’t think this is where the world is going.



AngularJS – intro

AngularJS is a Javascript framework from Google. It’s goal is to display data in a web page based on the MVC, and related paradigms. It was built with the idea of being able to make the connections between, data and UI, apparent and easy to manage.

I just began with it a day ago, so take everything here with a grain of salt. I’m sure I’ll cringe at this a month from now. I’m just writing this all down to try and get it all straight in my own head.


Directives are attributes, that act as hooks for AngularJS. Assigning a Directive to a tag creates link to that tag and it’s contents to AngularJS.

AngularJS defines many built in Directives. These all begin with ng-. For example, ng-app, and ng-model. These can, optionally, be prepended with data- for validation if you like. For example: data-ng-app, and data-ng-model.

You can also write your own Directives.

Here area  few Directives.

The ng-app directive tells Angular which part of the page it should manage. It could be placed in the html tag to manage the entire page, or on the body or div tag to manage a smaller realm.

Where this tag is placed determines the document root for Angular. Placing the ng-app directive on a tag other than the <html> tag will limit the scope of the Angular app to that region of the page.

Include an optional module name as a value to this attribute. For example: ng-app=”moduleName”.

The ng-init Directive initializes data. Usually you’ll want to handle this with a Controller.

The ng-controller directive attaches a controller to DOM element. A controller is a Javascript object that will manage data displayed in that region.

The ng-repeat directive tells Angular to copy the elements within the repeat element a number of times. It will populate this “template” element with data from the model.

Within ng-repeat Angular defines $index, $first, $middle, and $last. $index holds the the index of the repeated element. While $first, $middle and $last are booleans, true when the element is the first, middle or last element.

The {{}} defines a template expression. The {{ and }} can thought of as defining the area where Angular will write data. The expression inside can be thought of as modifying or defining how the data is written.

The ng-model attribute allows you to define connection from the DOM to model data. In the case of an input field modifying the input modifies the model data directly.

The | defines a filter to be applied to the content of a {{}} template. There are several built in templates, and you can define your own. The example above formats item.price as currency.

The ng-click directive sets up a click action that will call on JS we define. The handler function should be part of the $scope of the controller that contains this ng-click.

Note that $index is a variable defined by ng-repeat.

The ng-bind attribute can be used to bind a view element to a model value. This works the same as use the {{}} template syntax. Where the {{}} syntax will show the {{}} for a moment when the page initially loads the ng-bind directive will not. Making this good for elements that will show initially.

Use ng-change to call a function defined in the $scope of the elements controller when a form element changes.

Use ng-submit to call a function when a form is submitted.

Images and Anchors are special cases and have their own specific directives.

MVC – Model View Controller

MVC is a software design pattern that breaks functionality into three areas: Model, View, and Controller. This pattern is particularly suited to software that handles and manipulates data via user interface. Which makes it a good fit for Web apps. AngularJS turns HTML, CSS, and Javascript into a surprisingly good fit for this pattern.


Angular uses the MVC, or Model, View, Controller, paradigm. Where the Model represents data used by your program. For example, a list of user names, or a list of products with their price and description. The View is where data is displayed and represents the visual end of your program. The controller is the business side of your program. It contains the logic that manages data and facilitates translating data so it can be displayed by the View.

A Model can be as simple as a variable containing the number of times a button has been clicked. More often model data will be an array or object containing a list of values and properties.

A Controller might contain functions that controls the how a number is displayed. It might round the value off or format it any number of ways. More often the Controller will load an array of data and sort and filter before sending it to the View.

Views in Angular, are HTML. The view is essentially written in HTML and CSS, along with Angular’s templating system. Controllers are tied to views directly in the HTML as attribute names. This is a key feature of Angular that makes it unique.


Controllers handle processing model data.


The display data held by the model. Views in AngularJS are templates defined as snippets of HTML. These can be external files loaded into the app, or defined within the same file tags. Templates can all be defined as strings as part of a controller, directive or other module.


Model data should be defined in a “modules”. Use Angular’s module method to create a new module.


Services are singleton objects that provide global functionality to an app. Built in services begin with the $, such as $routeProvider, and $http.


Here’s the outline for an Angular page:

Use the ng-app directive in the HTML tag to declare everything in your document as part of the “app”. Load the Angular.js file at the bottom of the body tag to improve load times.

Templates and {{}}

Templates define the views your app displays. Templates are written as plain HTML with the addition of the {{ and }}. Expressions and references to model data are placed inside the {{ and }} to determine where that data will be displayed in a template view.

Templates can be defined as external html files, or tags written in the host file.


Expressions are Javascript like snippets of code that can be placed in the HTML of your page. Usually they fall inside of the template {{expression}} “tag”. But they can also be declared as part of a directive. Expressions support a lot of basic javascript but not everything.

Angular expressions are evaluated against the current $scope.

Angular expressions do not support loops and flow control like if statements.

Angular expressions are not parsed using JS eval(). Instead they are parsed using Angular’s special parsing function. This means that expressions that fail produce no output rather than an error or undefined.


Web apps revolve around text and data. Which often needs to be formatted in may different ways. AngularJS provides filters for this. Filters can be used in Angular expressions to perform formatting tasks.

Since expressions can be used directly inside templates it makes a nice works flow as you’ll be formatting model data in the same place it will appear in a view.

Follow and expression with the | and the name of a filter to apply the filter to a value of the expression.


Angular is really great with forms and handles them natively. Angular provides built in form validations service. Model data can be tied directly to the value of form elements. This is a two way binding. That is a changing the value in a form element, typing into a field instance, will update the Model, and updating the value in the Model will change the value that appears in it’s asscociated form element.

AngularJS provides many directives that apply directly to form elements. Here are three:

  • required
  • ng-maxlength
  • ng-minlength

Add a controller to a form to handle validation. Angular provides $valid, a boolean, which represents the validation state of the form.

Assigning model data as values for form elements means the form data is accessible in your controllers through the model.

Data binding

Data binding in Angular is two way. Any View element that is bound to Model data will show the current value at all times. If the value in the Model changes the view updates, if the value changes via the View, in the case a of a form element, the value stored in the Model changes also.

Dependency Injection

Dependency injection is a system of sharing services with modules. Essentially, from what I’ve gathered so far, and knowledge is limited at this point, dependency injection is boils down to sending a reference to a service as a parameter to a controller function.

Most of the information here was gleaned from AngularJS By Brad Green, Shyam Seshadri Publisher: O’Reilly Press. Get at the library

Corona – Display objects properties practice

Here’s a few ideas if you want to practice your programming skills.

Let’s talk about display objects. All of the display objects act the same way and support the same properties. This includes, images, shapes, like the rectangle and circle, text objects. These properties also apply to the group. Think of a group as an empty display container that you can add other objects. It’s like a layer in Illustrator.

Display objects have the properties that determine how they are displayed. Properties are always accessed with the dot (.), and you set their value with the equal sign. For example: = value

Here’s a list of properties.

x – horizontal position

y – Vertical position

xScale – horizontal scale

yScale – vertical scale

anchorX – horizontal position of the object’s anchor point

anchorY – vertical position of the object’s anchor point

Here’s a few things to try with this. Create a new project with the default settings. In main.lua add the following at the top.

This should create a rectangle in the upper left corner. The first two parameters (0,0) set the x and y initially. The center of the object is located at the upper left corner.

Set some other properties.

Try changing these values to see what happens. You could have done all of this with any other type of display object like text, or images.

Generate a random number with math.random(). This can be used in two ways. Either to generate a random number from 0 to 1, for example 0.826727384. Or generate an integer value between any two numbers. For example 1 to 6. Here’s what this would look like in code form:

You can test these in the terminal with

Apply this to the box:

You can make this interactive with:

Tap the box and it moves to a random position. Randomize the y property of box on your own.

This would be more interesting with some motion. Modify the function above to look like this:

Animate the y on your own.

Let’s make this more challenging. Make 10 boxes. Use a loop. The basic loop syntax looks like this:

so to make 10 boxes. Use the following.

You should have 10 boxes all over the screen. Here’s where things get interesting. Since you have declared box as local within the loop this variable is local to that code block it isn’t accessible outside the loop.

Try this, remove all of the other code except for the code below.

You should get an error message pointing to the last line. Read the error message closely, it should include the line number for the last line: box.x = 100. We can’t access box, since it’s local to the loop!

Beside this which box would be accessing? We’d like to get to tap on any of the boxes and have them move and spin to a new location.

Add this function above the loop.

Add the text in red to the loop. This still won’t work. Box is not accessible remember? We’re talking about this line in move box:

The event object has a reference to the box that generates the event. Each box has been assigned an event listener. When tapping a box, that box will generate the event. In this way move_box will know which box to move. Edit the line above:

The event variable is a table containing properties describing the event that just occurred. One of those properties, target, contains a reference to the object that generated the event. Try it now.

PHP – If statements

Most programming languages provide a conditional statement of some kind. PHP provides an if then else, the syntax of which is very similar to Javascript and other languages. In PHP the if statement has a few extra features.

Let’s start with the basic if statement.

Here if the condition is  evaluated to true the code block is executed. You can add an alternative code block that will be executed if the condition is evaluated to false.

Here the the second code block is executed when the condition is false.

Here’s a couple real world examples.

In this example if the variable $_GET['category'] has been set the value is printed to the page.

We can add an else to this:

Here if the $_GET['category'] variable is set, then it is printed to the page, otherwise (else) the message “Category not set” is printed instead.

Since PHP is an html embedded language you will often find that you want to print HTML and other text to the page as part of the if and else. Using echo is okay in some cases. Fo example:

In other cases the situation gets more complex. For example imagine that you are check if someone is logged in, and if not you want to display a form:

Printing the form using echo is awkward. I didn’t write the entire form above, use your imagination, it can get a little ugly; worst of all everything is inside the quotes so you don’t get any color coding or other help from you editor.

In these cases there is a better way. PHP allows you to close PHP and reopen the PHP tag anywhere. Here’s an example:

Here we exit PHP after the else statement, so the form can be written as standard HTML. Not that that the if statement has the it’s complete syntax within the <?php ?> tags. The lone } looks a little odd inside of <?php ?> on the last, but this completes the syntax so everything is okay.

Alternately you could write the same statement above with this alternate syntax.

Corona – Debugging

Having trouble with your Corona projects? Here’s a great article with lots of advice on debugging:

Touch screen interaction design challenge

Back in the olden days, we’re talking the 90s, there was shockwave. This was before Flash. Shockwave was the web component of Director.

At at the time there was a site Playcom if I recall, that had many Shock wave games some of which were pretty good. One of the games I thought was well conceived, though difficult to play, was called Tune Inn. The concept was a record store where you made records for customers. Customers wore shirts in a color  and the idea was to make records in colors that matched. You played two characters Pekka and Moniq. Pekka helped customers at the counter while Moniq made records upstairs. Heres a picture.


The original game used the keyboard to control and switch between characters. Here’s the challenge, how would you adapt this to a touch screen game?

Sprite reference material

Here’s a link to a site with a lot of sprites sheets for reference.  Ever wonder how those animations and tiled backgrounds were made? Taking a look at some of the art here will give you a good idea.

Sidescrolling endless runners

If you haven’t played Canabalt, you should give it a try. This is one of the games to define the single button endless runner type games. the original was made in Flash. There’s also an IOS and Android version. I hear the Android version is better with different worlds and things.

Essentially the gist of the genre is that you are running forward avoiding obstacles. things get tougher as the game progresses. There’s lots of variation. I’m linking to an article here by the author of Canabalt talking about what went into making Canabalt and the decisions for different screen sizes, and game mechanics. Very informative if you wanted to make a similar game.

CSS Sprites

Using spritesheets with HTML is getting popular. The advantage is only having to load a single image file, rather than a separate image for each image element.

Here’s a link to an online tool that will make spritesheets and give you the coordinate data in CSS.