My AngularJS snippets for Visual Studio

I use Visual Studio as my main IDE. Mostly because I come from a .net background – so my view is probably biased – but I also think that it’s one of the most complete IDE out there. If you can afford the cost, that is.

For my AngularJS applications, I quickly felt the need for snippets in order to avoid typing repetitive code. After seeing John Lindquist typing at speed of light in his videos, it became obvious that I had to create my own snippets.

I’m sharing these snippets today, so feel free to use them.

AngularJS controller

(function () {
    'use strict';

    var controllerId = '$toReplace$';
    
    /**
    * Purpose: $description$
    */
    angular.module('$comanyName$.$moduleName$.controllers').controller(controllerId, ['$$scope', controllerFunc]);

    function controllerFunc($$scope)
    {

    }
})();

Let’s analyse this snippet.

  1. I take a module design pattern approach. Although this is not required when using AngularJS, I consider this as good practice.
  2. Again, as a good practice, I make sure the strict mode is turned on.
  3. Giving my controller an id is useful when logging errors. This is a trick I learnt from John Papa.
  4. Then comes the controller definition. Note that the module is defined elsewhere, in an index.js file – see my post about structuring an AngularJS application for more details.
    Although I’ve made the company’s name a dynamic field, it would normally be hardcoded in the snippet itself.
    I inject the $scope variable – note the double ‘$’ for escaping the angular $ prefix – into all of my controller since I always find a use for it.
  5. Finally the code of the controller is defined in a controllerFunc function. All of my controller’s function have the same name and because I use a modular approach, I don’t have to worry about finding original names 🙂

All of my AngularJS snippets follow the same pattern.

AngularJS directive

 (function () {
    'use strict';
	
	var directiveId='$directiveId$';
    /**
    * Purpose: $description$
    */
    angular.module('$companyName$.$moduleName$.directives').directive(directiveId, ['$dependency$', directiveFunc]);
	
	function directiveFunc($dependency$) {
        return {
            restrict: '$directiveType$',
            templateUrl: '$templatePath$',
            scope: {

            },
            link: function (scope, element, attrs) {
                
            }
        };
    }
})();

AngularJS filter

(function () {
    'use strict';
	
	var filterId='$filterId$';
    /**
    * Purpose: $description$
    */
    angular.module('$companyName$.$moduleName$.filters').filter(filterId, filterFunc);
	
	function filterFunc() {
        return function ($parameter$) {
            
        };
    }
})();

AngularJS service

(function () {
    'use strict';

    var serviceId = '$toReplace$';
	/**
    * Purpose: $description$
    */
    angular.module('$companyName$.$moduleName$.services').factory(serviceId, [serviceFunc]);

    function serviceFunc()
    {

    }
})();

My snippets can be downloaded here.

mongodb – couldn’t connect to server

Tonight I was about to spend some great time trying out this very exciting Breeze-MEAN sample that the breeze team put together.

Unfortunately I was stuck at step 2 and spent the rest of my evening trying to figure it out.

Step 2
### Extract the database
Extract the Zza application’s MongoDB database in *zza-mongo-database.zip* to your MongoDB data directory.

Well, extracting the database files was pretty easy if you ask me 🙂

-zza.ns
-zza.0
-zza.1

Then I launched the mongo shell and my troubles started:

MongoDB shell version: 2.4.2
connecting to: test
Sat Apr 20 07:22:09.390 JavaScript execution failed: Error: couldn't connect to server 127.0.0.1:27017 at src/mongo/shell/mongo.js:L112
exception: connect failed

What the heck ?

After trying out all suggested solutions that I found on the internet, including repair and even reinstalling mongodb, I figured out that it was a privilege issue.

When I extracted the breeze db files, they were associated with my local user account:

$ ls -l
-rwxrw-rw- 1 sam  sam   67108864 Feb 10 19:53 zza.0
-rwxrw-rw- 1 sam  sam  134217728 Feb 10 19:53 zza.1
-rwxrw-rw- 1 sam  sam   16777216 Feb 10 19:53 zza.ns

I’ve noticed that my other database files are owned by the mongodb user. So I tried the following:

$ sudo chown -R mongodb zza.*
$ ls -l

-rwxrw-rw- 1 mongodb sam   67108864 Feb 10 19:53 zza.0
-rwxrw-rw- 1 mongodb sam  134217728 Feb 10 19:53 zza.1
-rwxrw-rw- 1 mongodb sam   16777216 Feb 10 19:53 zza.ns


And now it works !

$ mongo
MongoDB shell version: 2.4.6
connecting to: test
Server has startup warnings: 
Mon Feb 10 20:49:11.351 [initandlisten] 
Mon Feb 10 20:49:11.351 [initandlisten] ** NOTE: This is a 32 bit MongoDB binary.
Mon Feb 10 20:49:11.351 [initandlisten] **       32 bit builds are limited to less than 2GB of data (or less with --journal).
Mon Feb 10 20:49:11.351 [initandlisten] **       See http://dochub.mongodb.org/core/32bit
Mon Feb 10 20:49:11.351 [initandlisten] 
> show dbs
local	0.03125GB
zza	0.203125GB
> use zza
switched to db zza

debugging a nodejs application

I recently found myself messing about with nodejs. I think this is going to be my new toy for the coming months. My goal is to learn writing full-stack JavaScript applications with MEAN (Mongodb, ExpressJS, AngularJS, NodeJS).

After installing nodejs, I wrote a Hello World application… and I was bored with it pretty much right away :p So I started writing something more complicated and I quickly felt the need to debug my code.

Get to the point, how do I debug a nodejs application ?

Ok, first thing first is to install node-inspector. This will enable us to debug our application in Chrome. Yes, in Chrome.

Make sure you use the -g option in order to make a global installation. This way, node-inspector will be available to all your nodejs applications.

>npm install -g node-inspector

Next, run node-inspector :

H:\>node-inspector
Node Inspector v0.7.0-2
   info  - socket.io started
Visit http://127.0.0.1:8080/debug?port=5858 to start debugging.

In some cases, your port 8080 might no be available, in which case you’ll get the following error:

Cannot start the server at 0.0.0.0:8080. Error: listen EACCES.

Not to worry, just start node-inspector on a different port like that:

H:\>node-inspector --web-port=4500 

Here I just started node-inspector on port 4500.

node-inspector is now running. Open Chrome and browse to http://localhost:8080/debug?port=5858. You should see something similar to this screenshot:

node-inspector

Have you noticed the error message in the console ? Basically the debugger is running, but we have not launched any program to debug.

Let’s do that. If you do not have an application, let’s create a hello-world.js file (hurrah….) and paste that code:

    console.log("hello world");

Next, create a package.json file and paste this content:

{
  "name": "hello-world",
  "version": "0.0.1",
  "private": true,
  "scripts": {
    "start": "node hello-world.js"
  },
  "dependencies": {
   
  }
}

Ok, we’ve got our nodejs application, now let’s debug it.

From the command prompt, type the following:

H:\>node --debug hello-world

If everything went well, you should see this output:

H:\>node --debug hello-world
debugger listening on port 5858
hello world
H:\>

The problem is that the program runs so fast that we did not have enough time to start debugging in Chrome.

Using the -brk option we are forcing the program to stop on the first statement:

H:\>node --debug-brk hello-world
debugger listening on port 5858

Now go back to Chrome and hit F5 to refresh the page. And voilà, you can start debugging:

debugging hello-world

Restarting node automatically with nodemon

When developping with node, the server has to be restarted whenever you make modifications to your source code.

This can be avoided with the nodemon package. It basically watches your code for changes and automatically restart your server.

To install it:

>npm install nodemon -g

Here, I’ve installed the package globally but you can also install it locally to your application.

Below you can see the node server restarting after the source code was modified:

nodemon

STRUCTURING YOUR ANGULARJS APPLICATION – PART II

DOWNLOAD THE CODE

This is the second part of my tutorial on how to structure an Angular application. You can read Part I here, if you haven’t already.

Several people emailed me asking for a demo of my application structure proposal. I therefore put together a very simple demo that illustrates how to divide your Angular application into business modules.

The application will:

  • Allow us to manage customers
  • Allow us to manage products

In my point of view, Customer and Product are two different entities. Although they are related somehow – a Customer can order Products – controllers and views for managing these entities should not be mixed up. The application should have screens dedicated to CRUD (Create Read Update Delete) operations on Customers and screens dedicated to CRUD operations on Products.

Application structure

Notice that this structure is slightly different from the one explained in part one. It doesn’t change much but because I’ve used the Yeoman project generator for this demo, business modules and the app.js file are in located in a scripts folder inside the app folder, instead of being in the app folder directly.

1

Notice that we have a module for Customer, a module for Product and a Shared module, which I will explain later.
Then we have the app.js file. Let’s take a closer look at it:

angular.module('samdev.angularStructureSampleApp', [
  'ngCookies',
  'ngResource',
  'ngSanitize',
  'ngRoute',
  'samdev.customer-module',
  'samdev.product-module',
  'samdev.shared-module'
 ])
  .config(function ($routeProvider) {
    $routeProvider
      .when('/', {
        templateUrl: 'views/main.html'
      })
      .otherwise({
        redirectTo: '/'
      });
  });

As you can see, it is very simple: it defines basics routes and the dependencies required to run our application, including our business modules.

Business modules structure

Let’s start with the Customer module:2

Notice the index.js files at the root of the module folder and in each sub-folders (except for views). Let’s examine the one at the root folder:

angular.module('samdev.customer-module',
        [
            'samdev.customer-module.controllers',
            'samdev.customer-module.directives',
            'samdev.customer-module.filters',
            'samdev.customer-module.services'
        ])
    .config(function ($routeProvider) {
    $routeProvider
        .when('/customers', {
            templateUrl: 'scripts/customer-module/views/customers.html',
            controller: 'customers.ctrl'
        })
        .when('/customers/:id/detail', {
            templateUrl: 'scripts/customer-module/views/customers.detail.html',
            controller: 'customers.detail.ctrl'
        });
});

Here we’ve defined our Customer module by injecting dependencies and providing routes specific to this module – we have a route for showing a list of customers and a route for showing details of a specific customer.

Our dependencies are simply the controllers, directives, filters and services specific to the Customer module. Each one of these modules is defined once, in the appropriate index.js file. For instance, the controllers module is defined in the index.js file located in the controllers folder:

angular.module('samdev.customer-module.controllers', []);

The Product module is very similar. This way it is very easy to keep code consistent across business modules.
I’ve added a Price filter to the filters module, just to illustrate how this can be done.

3

The Shared Module

Earlier, I’ve mentioned the Shared module. Why do we need this module at all ?

Let’s take a look at the application:
4

The menu in the top right corner does not really belong to either the Customer or the Product module. It is more a feature global to the application.

Therefore it is a good idea to create a directive for this menu and put it in the Shared module:
5

Just remember to avoid using the Shared module as a mixed bag – use it sparingly.

DOWNLOAD THE CODE

Hopefully this makes sense but let me know if anything’s unclear!

Code formatting DOES matter

This is just a rant post towards developers who don’t give a s**t about code formatting.

Consider the following code:

function MyDayIsBoring(b, c)
{
  if (!c)
   return

  var sum=b+c



  return sum;
  }

One word to describe it: UGLY !

Let’s see what’s wrong with this code:

  1. Function naming
  2. Giving an explicit name to your function helps figuring out what it is supposed to do. Naming your function MyDayIsBoring only tells us that you should probably start looking for a new job.

  3. JavaScript is camel case.
  4. It’s just a convention to follow. So unless you’ve set specific guidelines within your company, all developers should stick to this convention.

  5. Curly brackets positioning
  6. Again, a convention. In JavaScript, opened curly brackets should follow the statement on the same line.

  7. Semicolons are not just for smileys 😉

    It used to be mandatory. It’s not anymore. But that doesn’t mean you should skip semicolons. They make your code clearer and in some cases you may even get warnings if strict mode is enabled.
    Moreover some Minifiers/packers/compressors rely on the semicolon for processing your scripts.

  8. Make your code readable
    var sum=b+c
    

    should really be

    var sum = b + c; 
    

    Spaces are really important to make your code readable. But on the other hand do not abuse line jumps !

  9. Last but not least, comment your code !
  10. There is no need to comment every single line of code. In fact, good code often don’t require a lot of comments. But having a description of the function, of the arguments and of what the function returns, certainly is a good idea.

    Let’s apply all these recommendations to our code:

    /**
     * Adds two numbers
     * @param {Number} a 
     * @param {Number} b
     * @return {Number} sum
     */
    function add(a, b){
      if (!b){
        return;
      }
    
      var sum = a + b;
      return sum;
    }
    

    Note that for comments, I’ve used jsdoc style, which will let you generate documentation based on comments.

    Also, most IDEs offer shortcuts for auto-formatting your code. Do yourself a favor and abuse them ! I use Visual Studio and I always do a CTRL-K CTRL-D before checking in my code to source repository.

Array functions that I use the most

I use arrays all the time. Sometimes though, I forget the syntax for a particular function or even the actual name of the function that I’m supposed to use in order to achieve the desired result.

So this post is aimed at listing Array functions that I use the most. I will cover several use-cases using both the native Array methods (when possible) and the Underscore.js‘s way. If you don’t know Underscore.js, don’t waste any more time and go download it. It’s a great library that will save you plenty of time instead of re-inventing the wheel.

This post will grow over time as I come across more use-cases that I want to remember. The code can be downloaded here and is meant to be run in a nodejs command prompt.
The zip file contains both the tutorial examples and the Underscore.js library.

This is the array we are going to work with:

var persons = [{name: 'Mike', age: '30'}, {name:'Sam', age:'34'}, {name:'Lucy', age:'27'}];

TUTORIAL #1 HOW TO FILTER AN ARRAY OF OBJECTS BASED ON A PROPERTY VALUE

We are looking for a person whose name is ‘Mike’.

  1. using JavaScript Array.filter native method
  2. var found = persons.filter(function(person){
    	return person.name === 'Mike';
    })
    
  3. using Underscore “where” method
  4. found = _.where(persons, {name: 'Mike'});
    

TUTORIAL #2 HOW TO EXTRACT A PROPERTY FROM AN ARRAY OF OBJECTS

We want to extract the “name” property of each person in the array.

  1. using JavaScript Array.map native method
  2. var found = persons.map(function(person){ 
        return person.name});
    }
    
  3. using Underscore “pluck” method
  4. found = _.pluck(persons, 'name');
    

    DOWNLOAD CODE

ui-select2 is always $dirty

I use the ui-select2 Angular wrapper for the select2 jQuery plugin. It’s great but it made my form $dirty each time the page is loaded.

This issue was already reported on github and there are fixes out there, but they only apply when the ui-select2 is used as a dropdown. I use it as an input, so I had to find my own workaround.

The trick was to force the form to be $pristine right after initialisation.

So in the ui-select2, I’ve added the following code at l. 141:

if (opts.setpristine && !isSelect) {
  elm.parent().controller('form').$setPristine(true)
  opts.setPristine = false;
}

Note the setPristine property on opts. The very first time this code is called, it forces the form to become $pristine. We make sure that later calls will not affect the form by setting setPristine to false.

The ui-select2 has to be initialized like this:

$scope.select2Options = {
     //more options here
     setPristine: true
};

and voilà 🙂

Passing a dynamic display field to the select2 jquery plugin

If you’ve never used the select2 jquery plugin, you should check it out. I use it for its tagging support:

tags

More specifically, because I develop with AngularJS, I use the ui-select2 directive, which allows binding a model to the select2 plugin.

Let’s say I have a list of products I want to bind to my select2 tags input. Using a AngularJS controller, I would define the list on the scope:

$scope.products  = [ {id: 1, text: 'camera'}, {id: 2, text: 'computer'}, {id: 3, text: 'shoes'}, {id: 4: text: 'table'}];

I would then bind the ui-select directive to my list of products like this:

This works great.

However it is very unlikely that in a real application the Product entity will have a property named `text`. What if my Product entity is defined as:

 Product { id, name } 

Well, that’s too bad because the ui-select2 directive, and ultimately the select2 jquery plugin, both expect the data source to have a property named ‘text’. It’s used as the display field.

So, how can I use a custom display field with the select2 ?

JavaScript is a dynamic language, and that’s what I love about it. The select2 plugin takes a number of options, such as maximumInputLength, multiple, tags, etc…. But nothing stops you from adding extra options to it. With AngularJS, you would typically set the select2Options like this:

$scope.select2Options = {
            multiple: true,
            simple_tags: false,
            width: '260px',
            createSearchChoice: function () { return null; },
            tags: [],
            displayField: "name"
 };

Note the displayField was set to “name”.

Next, the magic trick is to access the displayField using the JavaScript array notation. So if the old `text` property was accessed like this:

 data.text

you can now access the displayField this way:

 data[this.displayField] 

I’ve attached below my versions of select2.js and ui-select2.js. Feel free to use them !

select2

ui-select2

Structuring your AngularJS application – PART I

When I started writing Single-Page Applications (SPAs) using AngularJS, my first concern was how I was going to structure my code. I have enough experience with JavaScript to know that if you don’t tackle this issue right from the very beginning, you’ll end with spaghetti code before you know it.

AngularJS is quite opinionated when it comes to structuring an application. It follows the MV-* pattern (there are debates over MVC or MVVM, so let’s not get into that), with the addition of directives for augmenting the HTML language. This allows for loose coupling and separation of concern, which ultimately is great for refactoring and testing.

Yet, this does not answer the question: how do you structure your application ?

I have seen people writing ALL their Controllers in a single JavaScript file. How is that for code readability? I would not like to be the developer who is going to take over their code.
Sure if you’re building another Todo or Hello World application, you’ll be just fine. But in the real world that just doesn’t happen.

Instead I like to think of my applications as a collection of business modules. So I needed a way to structure these business modules in my application while keeping the MV-* pattern along with all the great features provided by AngularJS such as directives, factories, or even filters.

Application structure

The client-application logic is located in the /app folder at the root of the solution. It is divided into business modules, each represented by a folder.

top-level folder structure
top-level folder structure

The app.js file is the starting point of the AngularJS application. It is used for:

  • declaring the main module of the application
  • configuring the application
  • defining basic routes and states
  • running start-up configuration code

Business modules structure

Business modules are then made up of a well-defined folders structure to accommodate the various components of an AngularJS application (controllers, directives, etc…).

business modules structure
business modules structure

Each business module contains an index.js file. This is used for:

  •  declaring the module and its dependencies using AngularJS syntax
  • configuring the module
  • defining routes or states

AngularJS modules structure

Similarly to the business modules, each AngularJS module contains an index.js file for defining the module and its dependencies. E.g. for the BusinessModule’s controllers, the index.js file would look like:

angular.module('companyName.businessModule.controllers', []);

1.  Controllers should be named using the convention {name}.ctrl.js as shown below:

controllers naming
controllers naming

2.  Directives should be named using a camel-case convention, e.g. myDirective.js

directives
directives naming

3.  Filters (same as directives)

4. Services (same as directives)

5. Views

The  Views module does not contain an index.js file as it is not a module per-say, but rather a collection of html files.

Views should be named using the convention {name}.html as shown below:

views
views naming

Files ordering

The order in which JavaScript files are added to the page is important. AngularJS modules are defined in the index.js files and for that reason, all of the index.js files must be added before any other files of the app folder.

There are many ways to achieve that. You can do it by hand but it can be a bit tedious. In my case, since I rely on the ASP.NET MVC Bundling mechanism, it is just a matter of writing a custom orderer such as:

bundles.Add(new CustomBundle("~/bundles/app") 
   { Orderer = new AsIsBundleOrderer()}.IncludeDirectory("~/app", "*.js", true));
 public class AsIsBundleOrderer : IBundleOrderer
 {    
  public IEnumerable OrderFiles(BundleContext context, IEnumerable files)
  {
    files = files.OrderBy(x =>; x.VirtualFile.Name == "index.js" ? 0 : 1);
    return files;
  }
 }

To conclude

So hopefully this makes sense. I’m not much of a lecturer so if something is not clear, please leave a comment.

There are many ways to structure a SPA and I’m in no way saying this is the best approach. It’s just the one that works for me.

What’s your approach ?