AngularJS “&” directive scope properties

I’ve been a bit confused by ‘&’-type scope properties of directives, so I finally took a few minutes to play around with them in attempt to get to the bottom of things.

Paraphrasing the AngularJS docs, ‘&’ properties are meant to provide a way to execute an expression in the context of the parent scope of the directive.

That sounds straightforward, however the syntax and usage that I’ve seen in various examples around the web looked confusing and ambiguous at times, or seemed to introduce an odd sense of coupling and repetition.

Let’s start simple:

Everything looks fine, and easy to follow there. We’ve created a directive that executes an expression on click, provided by its parent’s scope.

Now let’s introduce some arguments to the doStuff function.

At this point, it starts looking like we’re coupling the controller’s functionality directly with the directive through doStuff‘s number parameter. This is the kind of example that has show up on some AngularJS tutorials, and was the original cause for confusion.

Anyway, let’s see what happens when we add a new parameter and play with the parameter names:

Now we can see that the arguments inside the declared HTML my-click-action="dooStuff(foo, bar)" must match up to those inside the directive template rather than the controller function $scope.doStuff = function(numberA, numberB) { ... };.

Here the declared expression my-click-action="doStuff(foo, bar)" is coupled with the controller via doStuff (by name and airity), but the actual arguments themselves fall within the directive’s usage of the expression. There is no direct coupling between the directive and controller after all (obviously!).

Some AngularJS notes from egghead.io’s videos

First off, all the credit credit and thanks goes to John Lindquist of egghead.io. If you’re interested in AngularJS, visit egghead.io and watch all of the videos (41 total as I’m writing this), they are well worth it for beginners, and people already using it alike.

While watching these videos, I decided to take some basic notes to serve as best-practice reminders.  I’d like to share what I’ve gathered, and annotate it with relevant links that go into deeper discussion.

Testing – set up a testing framework right away. The structure of AngularJS apps is modelled around modularity and dependency injection, making it inherently easy to test them. Do NOT skimp out on this. Get started with Jasmine.

The “Dot” – this one has been mentioned countless times. It’s a very simple pattern and very important for any AngularJS beginner. Essentially, it ensures that you access scope data from the intended scope, rather than overriding/shadowing the existing data somewhere up the prototypal inheritance chain. A thorough rundown can be found here.

Passing arguments to scope methods – rather than directly accessing the scope from within your scope functions, it’s best to define the function with a parameter, and pass the data in as an argument. Makes for better testing, and more declarative / descriptive HTML.

“&” scope properties on directives – This one isn’t really well described in the docs, so be weary. If I learn enough about them, I’ll share my thoughts here.

Arguments to directive link functions have a fixed signature - Unlike the parameters of Controller constructors, which are provided via dependency injection (become very familliar with this if you aren’t already) , directive functions have a fixed signature. For example, the link function always gets called with the following arguments: function(scope, iElement, iAttrs, controller). In general, if you see a parameter that begins with a $, it’s probably safe to assume that dependency injection is at play.

That’s it (for now).

JavaScript Date objects & user/browser timezones

The pains of working with timezones often hide themselves unless you’re developing something for an overseas client, or an international audience. This is especially true when working with dates that fall in-between days and/or weeks (ie. Sunday/Monday 00:00). Don’t forget to think about these edge cases!

Today a client mentioned that their calendar was displaying one week behind, whereas it was meant to display the current week. In essence, the backend was telling the client to render the calendar on the week that starts on ’2013/01/26′. This was done using JavaScript’s Date object, by constructing it with a datestring of ’2013/01/26′. Of course, this results in a date object of ’2013/01/26 00:00:00 UTC’, which can in fact appear to be a whole day back if the user/browser is set to a certain timezone (in this case, it came out to be ’2013/01/25 19:00:00 GMT-5′.

In order to avoid this issue, I came up with this simple JS helper function, that will convert a standard timezone-less date string (ie. ’2013/01/24′ or ’2014-04-10 10:23:45′) and convert it to the users current timezone:

Upgrading to SVN/JavaHL 1.7.x in Ubuntu

The most recent Subclipse Eclipse plugin (v1.8.x) requires SVN/JavaHL 1.7.x; however, running

sudo apt-get install libsvn-java

doesn’t quite get you there in Ubuntu.

Fortunately Dominik Stadler has created a PPA you can add to your software sources.
Before you continue, uninstall your existing libsvn-java:

sudo apt-get purge libsvn-java

Then proceed to add the PPA and reinstall the package:

sudo add-apt-repository ppa:dominik-stadler/subversion-1.7
sudo apt-get update
sudo apt-get install libsvn-java

You may also need to update your eclipse.ini to include

-Djava.library.path=/usr/lib/jni

(or possibly /usr/lib/i386-linux-gnu/jni or /usr/lib/x86_64-linux-gnu/jni depending on your system)

You can now upgrade Subclipse to 1.8.x
.. or save yourself the hassle and move to git :)

Lock Calendar updates coming?

One of the best reasons to jailbreak your iOS device was Lock Calendar (http://cydia.saurik.com/package/lockcalendar).. unfortunately there haven’t been any updates for iOS5 compatibility.

Recently however, the developer’s twitter feed (@volatile_dev) has breathed new life into Lock Calendars iOS5 era. Looking forward to installing it on 5.0.1 sometime soon!

Easy window resize in Xubuntu/Xfce!

Hold down ‘alt’ and right click+hold near the edge/corner of any window in Xubuntu/Xfce to resize without having to target those tiny pixel-sized borders. Sweet!

Parsing a JSON data stream

While browsing StackOverflow I accidentally stumbled upon this question.
The issue seemed like a simple but interesting one, and since google had no answers I thought it would be fun to give it a shot. The first iteration of my solution involved reading in strings of indefinite length, but it quickly turned into a overly-complex state machine so I stepped back and rewrote it with one-character-at-a-time input. You can find on github, under JSONCharInputReader.

JSONCharInputReader was designed to read in a JSON array, not object.
In other words, this will work:

[1, 3, 4, {"var": "val"}, ["array_item", "array_item"], ...

but the following will not:

{"key": ["array", 1, 2], "key2": "value", ...

To parse a JSON stream, create a JSONCharInputReader object and pass in your own implementation of the JSONChunkProcessor interface. JSONChunkProcessor defines one function:

interface JSONChunkProcessor {
    public function process($jsonChunk);
}

Clients implementing this can expect $jsonChunk to be valid JSON (as long as the JSON data being read in is valid itself). If the above array was to be read in, the decoded $jsonChunks passed to the processor would be as follows:


// Decoding 1
int(1)

// Decoding  3
int(3)

// Decoding  4
int(4)

// Decoding  {"var": "val"}
object(stdClass)#3 (1) {
  ["var"]=>
  string(3) "val"
}

// Decoding  ["array_item", "array_item"]
array(2) {
  [0]=>
  string(10) "array_item"
  [1]=>
  string(10) "array_item"
}

See example.php for a sample implementation of the reader, which can read JSON from the terminal by executing it with:

cat | php example.php

One notable limitation is that the $jsonChunks passed to JSONChunkProcessor will be first-dimension level elements of the incoming JSON array data stream. In other words, large objects or arrays will only be processed once the reader receives all of their data.

Simple SVN + FTP deployment script

This Python script provides very basic deployment functionality for simple, code-only updates and does not include database support.
The script, in a few words, does the following:

  • Executes an SVN export on the trunk or branch of a repository
  • Connects to an FTP server and uploads all files (and directories) that have a newer modification timestamp

To use the script you must configure your SVN repository root (in exupconfig.py) and FTP server credentials (by executing ftpaccounteditor.py). The FTP server credentials are saved in a local file (at a path defined in exupconfig.py). You have the option of encrypting any FTP password you save with the credentials; the encryption is handled by m2crypto module and requires a key (which you will be prompted for).

To download it, or clone the github repo go here.

Example (in a bash terminal):

# clone (or download and extract) the three files (exup.py, exupconfig.py & ftpaccounteditor.py)
git clone git@github.com:janeklb/exup.git
cd exup
vi exupconfig.py # edit exupconfig.py to match your settings
ftpaccounteditor.py # follow the inline instructions to add your FTP account settings
exup.py # and enter the repository you would like to deploy

Please post your problems / fixes / suggestions in the comments. I am new to the world of Python and your feedback is very welcome.

PHP code completion for anything in Eclipse + PDT

While I prefer to make quick changes to my code in a lightweight text editor, any lengthy coding session usually involves loading up an IDE in order to have access to all of the extra time-saving features. Code completion is one of those hard-to-live-without features that IDEs provide.. here’s a quick rundown showing how to get it working with any library or class (visible to your buildpath) to work under Eclipse + PDT.

The idea is very simple, although it is a bit of a trick as you have to apply it to any/every project you work on. Using PHPDoc’s @property you can reference any variable in a class (even if it hasn’t been declared) and associate it with a PHP Type. PDT does the rest!

For example, this is how you can add code completion to a CodeIgniter project’s controller classes:

Create a custom base controller (ie. MY_Controller — see the CI guide for more info) and at the top, in the class’ PHPDoc, add @property tags for any variable you want to use. Now any controllers you create, that extend MY_Controller, will automatically have code completion enabled for the variables you tag. In the following example, $load, $session and $output will be available.

<?php if ( ! defined('BASEPATH')) exit('No direct script access allowed');
 
/**
 * Base Controller Class
 * @property CI_Loader $load
 * @property CI_Session $session
 * @property CI_Output $output
 */
 
abstract class MY_Controller extends CI_Controller
{
// ...
}

Proudly powered by WordPress
Theme: Esquire by Matthew Buchanan.