AngularJS: Learning the First Steps to Build a Music Discovery App

AngularJS: An introduction

angularshield

I remember the first time I used AngularJS. It was a Sunday morning and I was in my parent’s living room, drinking coffee and watching a tutorial on Team Treehouse, something I used to do back when I had free time. I’d just finished my Higher Diploma in Web Technologies and was searching for a work placement so I could officially complete the course but I was uninspired by some of the roles on offer and under-prepared for the ones I was interested in. So I decided to take a step back and evaluate what exactly I was looking for from a work placement, and what exactly I wanted to do with my newly acquired skills.

I’ve never been design-oriented and found myself naturally more inclined towards server-side programming when I started to learn web development. I’m pretty good with HTML and CSS and picked up the basics of JS pretty easily and of course once I discovered jQuery I didn’t write a proper line of Javascript for months but I suppose I didn’t think of it as real programming. Client-side stuff was just a veneer that displayed the really interesting work that was being done on the server, and who really wants to spend hours thinking about what colours and shapes to use on a site? Not me and to a certain extent that’s still the case. However, that Sunday morning in my parent’s house I was surprised to find myself really enjoying the tutorial I was following and the things I was able to do with AngularJS.

It just seemed so much more substantial than the javascript I’d written before. Not just adding some cool on-click event or validating form input, AngularJS had models and controllers, and for me, coming from a Ruby on Rails background, that gave it a sense of importance that I hadn’t encountered in client-side programming. Before using AngularJS, I was used to working with a couple of HTML pages, a stylesheet and one or two javascript files that contained all the code necessary for the site/application but trying to work that way in AngularJS is impossible. Even the way an AngularJS app is structured made me feel like it could be used for something infinitely more serious than any client-side programming I’d done before.

AngularJS App Structure

A relatively simple AngularJS app folder structure

AngularJS encourages a modular structure, where you can/should have a separate file or directory for Directives, Controllers, Services, Filters or anything else you want. This post by AngularJS core contributor Brian Ford is a great place to start thinking about app structure but you could also use Yeoman’s AngularJS Generator or the AngularJS Seed app

I quickly googled for other client-side frameworks and tried out various tutorials, mostly creating simple To-Do list apps using Ember, Knockout, Backbone and Batman but none of those frameworks stuck with me like AngularJS did. Maybe it was the endorsement from Treehouse and the fact that their tutorial was interesting and demonstrated consuming an API and not just building yet another To-Do list app, maybe I fell for the hype and was blinded by the fact that AngularJS was developed by Google, but I quickly decided that it was what I wanted to focus on. I began to look for places in Dublin that were using it which proved difficult, but imagine my delight when a day or two later I received an email from Alex here at seevl about an opportunity he had for an intern to come in and work on the new version of the app. While the previous one was pure JS and jQuery, the latest version used AngularJS and Alex wanted a new intern to join the team to help out before the launch.

And so after a quick meeting and a somewhat botched attempt at creating my first unique AngularJS app to show what I could do, I started working here in Dogpatch Labs with Alex and the crew on seevl a week later.

Seevl Animated Banner A - 728x90 CON1

Making sense of AngularJS

So my first experiences with AngularJS were pretty good; I was interested and motivated and excited to start my placement with an interesting and exciting company using the newest technologies. “This will be fun”, I thought to myself. Cut to a week later and I was still trying to make sense of the first task I was asked to work on for seevl. “This is not fun”, I thought to myself.

The accepted wisdom when it comes to AngularJS is that its learning curve is less curvy and more hockey-stick shaped, i.e. it starts off gently and you think everything is going great until you crash face-first into a gigantic brick wall which seems to rise infinitely high above you. My first reaction, and I’m sure I’m not alone here, was to throw myself against the wall again and again until I was worn out and broken. Of course, the only sensible approach is to take a step (or maybe a few hundred) backwards and eventually you’ll start to see the top of the wall and maybe even see a few obvious foot- and hand-holds that might help you on the climb to the top.

AngularJS

One of my first tasks was to research a problem we were having with authentication and routing in the app and as an introduction to using AngularJS it was both illuminating and incredibly frustrating. You can see a sample of the code below but have a look at Thomas Nordlund’s authRoute.js module and if you’ve little experience of Javascript, let alone AngularJS, you’ll probably feel the same mix of confusion and dread that I felt when I first looked at it. While an incredibly useful and elegant solution to the problem, it made very little sense to me but by slowly working through it and constantly referring to Stack Overflow, the AngularJS Docs and various blogposts, I gained a better understanding of the specific problem I was trying to solve as well as the problem of understanding AngularJS in general.

So while my overall understanding of Javascript and AngularJS started to improve I was still faced with new AngularJS specific problems everyday. AngularJS is packed full of useful features that make it easier to create complicated functionality and to appreciate it fully you need to embrace the AngularJS way of doing things. That involves understanding and correctly using AngularJS modules such as controllers, directives, services, filters, providers and more. While I won’t go into too much detail on each of these in this blog, I would like to point out the difficulties I had in understanding just how to use some of these aspects of the framework.

Digging deeper

Perhaps the biggest difficulty I had in coming from a more traditional design/development background was trying to limit my use of jQuery. The problem with using jQuery and AngularJS isn’t that they clash (AngularJS even includes a stripped-back version of jQuery called jQLite) but that the way I had been using jQuery doesn’t really conform with the AngularJS way. jQuery makes DOM manipulation very simple and my first thought was that I could manipulate the DOM in the same way through my AngularJS controllers. While this is possible, it’s not the AngularJS way. With AngularJS, your HTML document acts as a record of our view-based functionality and manipulating that record from our controllers makes it more difficult for a new developer joining the project to understand why the page is acting the way it does. AngularJS overcomes this problem through its use of Directives, a way to “teach HTML new tricks” or to allow us to create our own HTML elements and this allows us the added benefit of being able to re-use elements with their own logic built in on other pages in our app or other apps. Check out the carousels on seevl.fm to see the beauty of AngularJS directives in action.

Combining taste graphs and knowledge graphs for content personalisation

seevl.fm’s carousels were created using AngularJS directives

We can put all our DOM manipulation code in the directive and then simply call that in our HTML like we would any other element and when AngularJS renders the page it will load all the logic too. MAGIC!

You might find yourself wanting to include some jQuery plugins in your AngularJS app (our carousels featured above use the excellent BXSlider plugin) but using them with AngularJS is not as simple as it might appear. Luckily, there’s an easy way to do this and that is to wrap the plugin inside a directive. While the best solution would be to rewrite the functionality in a more AngularJS way, it’s often easier and quicker to copy and paste the code into a directives link function. However, it won’t always work straight away and you’ll have to do some experimentation to get everything working. For me, my first experiments with directives was wrapping the jQuery UI Autocomplete plugin in one to use in seevl. While it would have been better for me to try to rewrite the code it was beyond my skills at the time but it forced me to play around with directives and figure out where and why things were working or not working.

 

angular.module("directives", [])
  .directive('autocomplete', function() {
    return {
      restrict: 'E',
      replace: true,
      transclude: true,
      template: '< input type="text" / >',
      link: function(scope, element, attrs) {
        scope.$watch(attrs.list, function(value) {
        var item = element.autocomplete({
        minLength: 2,
        source: scope.search,
        open: scope.open,
        messages: {
          noResults: function() {},
          results: function() {}
        },
        select: function(event, ui) {
          event.preventDefault();
          return autocomplete_select(ui.item);
        }
      }).data('uiAutocomplete');
    }
  }
});

One of my first experiments with directives was wrapping jQuery UI autocomplete in one

 

A great place to start if you’re coming from a jQuery background is this Stack Overflow thread, which is a great overview of AngularJS’ features in general but specifically if you’re struggling to forget about jQuery.

By embracing the AngularJS way and using Directives to control your view, services to pass data between modules and controllers as the glue to hold everything together, AngularJS becomes much more pleasurable to work with. The road to gaining a full understanding of all that AngularJS has to offer is long and winding and by no means easy and while I’m nowhere near becoming an AngularJS expert I have been working hard and have come to appreciate the things AngularJS provides to help us build complex web apps with relatively little effort. Rather than going through the various AngularJS features and giving half- or just plain incorrect explanations, I’d rather give you some advice on the best places to start if you’re new to AngularJS.

Advice on resources

There are many problems with AngularJS but one of the biggest, especially for an AngularJS newbie, or for someone like myself with limited experience of software development generally, is the notoriously bad documentation. While there are attempts underway to make the docs more comprehensive and accessible, there are still some that offer little help to someone struggling to make sense of AngularJS in the first place. For example, the documentation for directives offer little in the way of an explanation for a novice developer. The same can be said for other AngularJS features such as Services and $scope but thankfully there is a large and constantly growing community of users to turn to when the documentation leaves you feeling more lost than when you began. Pro Tip: It’s easy to ignore them but the comments at the bottom of the AngularJS Docs pages often yield more answers to the docs themselves.

Obviously Stack Overflow is a great resource for all things code but it has a great AngularJS and Javascript community with pages of pages of interesting and creative responses to user questions. If Stack Overflow fails, you can always try the #AngularJS IRC channel: unfortunately for us here in Ireland, it seems that the IRC channel is most quiet in the middle of our workday and at it’s busiest when we’re tucked up in bed, but you’ll usually find someone who can help you out.

There are loads of great resources appearing every week for AngularJS fans but I’ll point out a few that were really useful for me early on. As I’ve said before, I really enjoyed Team Treehouse’s AngularJS Workshop video. It’s presented by Jim Hoskins who has an appreciation of AngularJS combined with a relaxed style that makes the content engaging but it’s only available to subscribers. If you’re willing to pay, I can’t recommend it enough.

Another great resource is thinkster.io which combines Jon Lindquist’s egghead.io videos (another great free resource, which now offers a paid Pro subscription) with the O’Reilly AngularJS book and direct references to the documentation. It was a great introduction to the more technical aspects of AngularJS and the site has grown in the past few months and now offers a MEAN stack tutorial which I haven’t had a chance to try out yet but which I hear is very good.

AngularJS has it’s own sub-reddit which is quiet but can be an interesting place to pick up random tips rather than to find answers to your questions. Similarly, it might be a good idea to sign up for the ng-newsletter if you like the idea of getting AngularJS tips sent straight to your inbox once a week.

Finally, the Year Of Moo blog offers some really interesting reading for anyone interested in AngularJS coming from a Rails background.

Looking forward…

I’m still relatively new to AngularJS but I’ve realised recently while speaking with some of my colleagues on the M. Sc. I’m pursuing just how much I have learned in the few months since I started working on seevl and a lot of that has to do with the fact that in many ways you are forced to delve deep into the documentation and source when something isn’t working as you’d expect. Coming from a Rails or jQuery background, it becomes second nature to google for a gem or plugin that will solve a particular problem you’re having, and while there are many useful AngularJS modules available on the web (Pascal Precht’s angularJS-translate immediately jumps to mind as one of the most useful I’ve encountered so far but you can browse hundreds of modules here) they often take a lot more effort to implement than installing a gem.

The best advice I can give is to embrace “the AngularJS way” of doing things. Get involved in the community, ask questions on Stack Overflow or the IRC channel, read about new AngularJS features even if you never think you’ll use them. In my time working with AngularJS on seevl so far we’ve managed to trim the original code base by approximately 70% by switching from a pure Javascript/jQuery implementation to an Angular implementation and made a really slick and usable application at the same time. I’m excited by the AngularJS team’s roadmap for the future of the framework and I’m looking forward to learning as much as I can and putting it into practice. Luckily, I have the support of a great team at seevl and hopefully we can continue to build something really cool that uses AngularJS to full effect.

 Seevl Animated Banner A - 728x90 CON1

For more updates follow seevl:

  

Enhanced by Zemanta
Tagged with: , , , , , , , , , , , , , , , , , , , , , , , , , , ,
Posted in Engineering, Music, Products