Using jsFiddle with AngularJS

AngularJS is an awesome framework and its google group is very active. AngularJS community figured out quite early that it is so much easier to collaborate having a live code snippet.

There are many code snippet sharing tools out there but the jsfiddle is great and is used very often by the AngularJS community.

This post tries to dive into several usage scenarios of jsfiddle with AngularJS framework. The aim here is to make sure that people can quickly and easily prepare their jsfiddle which is crucial for getting help from  the AngularJS community.

Start safe

The easiest way to have a working jsfiddle with AngularJS is to start from a template prepared by the AngularJS team: http://jsfiddle.net/IgorMinar/ADukg/. The jsfiddle under this URL is updated with each release so you can just bookmark it and use it a starting point for your fiddles.

One remark: when using http://jsfiddle.net/IgorMinar/ADukg/as a stating point make sure to fork it instead of editing the original one.

Configure your own fiddle

jsfiddle is simple to use but there are couple of settings that we need to get right. All the jsfiddle options that need to be configured are located inside one of the panels on the left-hand side. Now we will take a tour of panels that are important from AngularJS point of view.

Choose Framework

jsfiddle has built-in support for AngularJS which makes the whole process of creating a new jsFiddle rather straightforward. In is enough to choose AngularJS as a framework and no wrap (head) (this is very important, otherwise your jsfiddle won’t work properly!).

Manage Resources

By The “Manage Resources” tab allows us to add additional references to external JS / CSS files. This tab comes very handy if we would like to use AngularJS modules other than ng (ngCookies, ngResource, ngSanitize or test-specific ngMock, ngMockE2E), external libraries (jQuery, angular-ui) or some fancy CSS. The screenshot below shows a jsfiddle configured with ngResource and bootstrap CSS being added.

Info

Next comes the info tab. On this tab you can customize some ‘info’ settings (title, description) to your liking but the setting you want to really pay attention to is the one in the ‘Body Tag’.
Usually AngularJS is bootstrapped inside the <body> tag – this is where we do use ng-app directive. Now, if we do define a module we need to put its name in the ng-app attribute and we do this in the ‘Info’ panel. Here is an example:

If a module is not used we can simply put <body ng-app>.

Yes, you can!

I’ve noticed that people often think that jsfiddle is very limited and can be used to illustrate only the simplest use cases. While it is true that there are use cases that are tricky / impossible to show with jsfiddle you can actually get pretty far. Here I would like to demonstrate how to use jsfiddle with some “advanced” AngularJS constructs.

Partials

There is no support in jsfiddle for creating files, so we can’t prepare HTML templates as individual partial files. What we can do thought is to embed partials in the HTML panel with the script directive. Here is the example of using ngInclude with jsFiddle.

Routes and $location

Inspecting the result panel shows that jsfiddle is using a separate IFrame to present execution results. This means that we’ve got a separate “address bar” for our scripts and we can provide code snippets making use of:

xhr ($http, $resource)

Testing $http and $resource shouldn’t be much of the problem, here is the example of using MongoLab with $resource: http://jsfiddle.net/pkozlowski_opensource/mMRfV/.

It is worth noting that jsfiddle has an ‘echo’ service that will respond with whatever content was sent. Check jsfiddle help for more details: http://doc.jsfiddle.net/use/echo.html

There is more

There is AngularJS WIKI page that has number of other jsfiddle / plunker examples so you might have a look for inspiration. Be ware thought that some of the fiddles are quite ‘messy’ – even if those examples are super-interesting, often stunning!

Getting help, the smart way

Don’t get me wrong, I love helping people. I really like code and tricky problems. But sometimes I really don’t feel like responding to posts on the AngularJS mailing list and most of the time this is due to the following reasons:

  • no jsfiddle / plunker provided: if I see a post full of source code that I can’t run immediatally I’m less likely to look into the issue; the thing is that in most but trivial cases you need live code to debug to actually understand what is going on – if I’ve got a source code in a post I need to copy it to a jsfiddle / plunker myself and often I’ve got no time / energy to do this; fortunately, after reading this blog post, you should know how to prepare a working jsfiddle!
  • code example too big: we are all busy and have only limited amount of time to spare; I want to help but want to do it fast – the less code I’ve got to read the faster I will understand it, so:
    • try to have a minimal reproduce scenario, omit everything that is not essential to the problem / issue you want to discuss;
    • omit any noisy parts of HTML: don’t include body / head tags in the HTML panel, just configure your jsfiddle;
    • don’t include CSS if it is not essential to demonstrate your problem – unless you are showcasing something omit any CSS that is not needed. If you are exposing a problem it doesn’t need to be pretty – just needs to be fast and easy to understand. Attributes in HTML there are there only due to CSS (class, id etc.) just make the HTML bigger / harder to grasp.

Live Templates for angular.js in WebStorm

John Lindquist is a WebStorm master

Many angularians watched and loved John Lindquist’s video tutorials (if you haven’t seen them I would highly suggest checking them out: http://tv.jetbrains.net/channel/webstorm/angularjs). Those tutorials are excellent introduction to angular.js and directives writing but we can get out of them: WebStorm mastery.

One thing that was striking me while watching John’s video tutorials was how productive he was with the IDE. He would write code at the remarkable speed, using very few keystrokes. Earlier today I’ve decided to watch the mentioned videos once again,  focusing on productivity tips. This blog post is trying to decipher some of the trick played by John.

WebStorm plugin for AngularJS

John Lindquist is the author of the angularjs-plugin for WebStorm. For now the plugins add support for angularJS attributes inside HTML templates but is is well worth checking out as the plugin itself highly increases productivity while editing angular templates.

Black magic with Live Templates

While watching very carefully the video tutorials (sometimes re-playing 10 seconds fragments over and over again) I’ve realized that most of the productivity speed ups are result of the IDE mastery (code navigation, effective shortcuts and code-completion usage) and the extensive use of Live Templates.

Your first Live Template

Live Templates is the future in the JetBrains products that allows us to define … well, code templates. Of course there is more into it than just simple ability to pre-define code fragments so please check the full documentation at http://www.jetbrains.com/idea/webhelp/live-templates.html.

If you are not into reading JetBrains documentation, don’t worry – we are going to create our first Live Template just now. As an example lets use the ‘ngm‘ template: it will produce a module’s skeleton for angular.js.

To start creating a Live Template we need to select File -> Settings… in WebStorm (or use Ctrl+Alt+s) and then select the Live Templates. By default WebStorm is pre-installed with some templates grouped into different sections (HTML, JavaScript, …). I think that angular.js deserves its own section, so let’s create one. As soon as it is done we can start creating our Live Template with the following properties:

  • Abbreviation: ngm
  • Description: A new angular module without a config function

Then comes the most important part: a template itself. Let’s type in this:

var $moduleName$ = angular.module('$moduleName$',[]);
$END$

We can see that WebStorm is using dollar signs to introduce variables (like $moduleName$ in the above example). You can define as many variables as you like, but there are also built-in variables available (the $END$ variable indicates where the cursor will end up after we are done with filling-in other variables).

To have our first Live Template ready to use we need to remember to define a context for this template: in our case it is JavaScript. The screenshot below shows the effect of our efforts:

The new shiny ngm is ready to use, it is enough to go back to a JavaScript editor, type ngm, press TAB and here you go:

Live Templates for AngularJS

All templates described here are hosted on GitHub

Based on John’s video and my own experience I’ve combined a list of useful Live Templates and put them in the GitHub repository. Below is the full list of available templates (names and abbreviations might have changed!) .

The basics

ngc – a controller function

var $controllerName$ = function($scope) {
$END$
}

ngf – a function in a scope (to be used in a controller)

$scope.$functionName$ = function() {
    $END$
}

ngm – a module

var $moduleName$ = angular.module('$moduleName$',[]);
$END$

Directives

ngdl – a directive with the link function

.directive('$directiveName$', function($directiveDeps$) {

    return function(scope, element, attrs) {
        $END$
    }
});

ngdc – a directive with  the compile function

.directive('$directiveName$', function factory($injectables$) {
  var directiveDefinitionObject = {
    $directiveAttrs$
    compile: function compile(tElement, tAttrs, transclude) {
      $END$
      return function (scope, element, attrs) {
      }
    }
  };
  return directiveDefinitionObject;
})

lf – a link function

function (scope, element, attrs$ctrl$) {
$END$
}

cf – a compile function

function compile(tElement, tAttrs, transclude) {
      $END$
      return function (scope, element, attrs) {
      }
}

sem – scope, element, attrs arguments in the linking function

scope, element, attrs$END$

There is more

I’m sure that there are more useful Live Templates to be defined so please, share your ideas! On my side I will keep updating the GitHub repository with any new useful templates.


Follow

Get every new post delivered to your Inbox.