Month: June 2015

Leonardo da Vinci - Anatomical studies of the shoulder
Leonardo da Vinci – Anatomical studies of the shoulder

I am a big fan of doing tutorials and courses online. I believe there is a lot of value in them. So much value in fact that I wrote an entire post on it. However you can read all the art books in the world, watch all the art videos on youtube and it won’t make you much better at creating beautiful paintings. There is value in learning about techniques and approaches however the true way to become a better artist is to do art. Your first paintings are going to suck but you just need to be persistent and carry on. Slowly as you paint more, your paintings are going to suck less until one day you look back and you have a body of work that has increased in quality over the years.

The same is true with all skills, you want to improve your writing, start a blog and write. Make peace with the fact that at first you are going to suck (and suck for a long time, I’m talking from experience here). Each time you write however you get better.

I’m not saying you should mindlessly churn out mediocre crap, you need to keep trying to improve, but the best way to improve is to actually DO something and critically look at it and start thinking about what you can improve. Do you need to work on your Grammar? Is your paragraph structure wrong? Are you relying too much on questions to make a point? Are you asking yourself these questions?

Art and Fear

There is a famous book Art and Fear by David Bayles and Ted Orland which I highly recommend you read. One part really stood out for me. It’s about an experiment a ceramics teacher ran on his class.

“The ceramics teacher announced he was dividing his class into two groups. All those on the left side of the studio would be graded solely on the quantity of work they produced, all those on the right graded solely on its quality.

His procedure was simple: on the final day of class he would weigh the work of the “quantity” group: 50 pounds of pots rated an A, 40 pounds a B, and so on. Those being graded on “quality”, however, needed to produce only one pot – albeit a perfect one – to get an A.

Well, come grading time and a curious fact emerged: the works of highest quality were all produced by the group being graded for quantity!

It seems that while the “quantity” group was busily churning out piles of work – and learning from their mistakes – the “quality” group had sat theorizing about perfection, and in the end had little more to show for their efforts than grandiose theories and a pile of dead clay.”

In essence the people who were charged with producing a lot of quantity ended up creating the best quality pots. Not because they were better potters(?) but because they learnt by doing, not by reading up on theories or watching pottery youtube videos. Their first pots probably sucked, they moved on and with each iteration their pots sucked less.

Don’t fear failure

I wrote a post about failing and how to fail faster I would suggest you read it. Tutorials and online courses don’t lead you down wrong paths. You don’t really fail following a tutorial. However sometimes it’s the wrong path and figuring out where you went wrong where the best learning is done.

One of the biggest reasons we fear failure is because we are scared of what people will think about us. It’s an interesting dilema. We don’t want to try things because we are scared what people will think if we suck, but we suck at doing things because we are scared to try them. The truth is that when you fail people will speak about you, but I would be willing to bet that the those are the ones who are not doing anything and are commentating from the sofa. The people who do things know how hard it is to produce and won’t think badly of you if you try and fail. So does it really matter?

Leonardo da Vinci - Female head (La Scapigliata)
Leonardo da Vinci – Female head (La Scapigliata)

Finish things!

It’s important to finish what we start, some of the best life lessons come from finishing something. Finishing is a practical habit that you learn best by doing. Don’t get discouraged if your first draft is bad (my final drafts are still bad, but I try to improve with each post). You are building valuable skills and practicing things you love.

You have to finish. So what if that painting isn’t that good don’t abandon it. Finish it, learn from it and try again on your next one, a little better.

Finally

Set goals for yourself but you need to understand that goals are made up of day to day tasks, day in day out you work toward your goal, improving each time. Getting better with each iteration.

Until next time. May you improve a skill you love each day a little bit.

-R

AngularJS Directives
Angular Directives

Last week I wrote about AngularJS on a high level. This week I am going to focus on AngularJS directives, what makes them so good, what to look out for and how to create your own simple directives. All the code in today’s example is available on GitHub.

Pre-Prelude

Directives are really powerful because they allow us to define all the DOM manipulation and changes we need inside the HTML code. The temptation to mix DOM manipulation code with business logic code is lessened, which makes code easier to read, test and debug. When we write our own directives they will by default be separated from the business logic in their own directive files.

Prelude

Every good journey deserves a prelude, so for us it starts with a simple scenario. We have a service which provides us with a list of best-selling albums in JSON (I wrote a bit about JSON here). The data we get looks like this:

{
  "albums" :
  [
    {
      "name" : "Thriller",
      "artist" : "Michael Jackson",
      "released" : "1982",
      "instock" : true
    },
    {
      "name" : "The Dark Side of the Moon",
      "artist" : "Pink Floyd",
      "released" : "1973",
      "instock" : true
    },
    {
      "name" : "Bat Out of Hell",
      "artist" : "Meat Loaf",
      "released" : "1977",
      "instock" : false
    },
    {
      "name" : "Their Greatest Hits",
      "artist" : "Eagles",
      "released" : "1976",
      "instock" : true
    }
  ]
}

We are going to be creating an Angular website which will be worth millions some day (no promises on that last part). This website will list all these albums for people to admire. Also we might be selling the albums one day so the JSON will also tell us if we have the album in stock or not.

It will look something like this:

That Code Corner Music Screenshot
That Code Corner Music multi million dollar website!

This site might not win many design awards but it will be enough to help us work through how Angular directives work.

Directives in Action!

Once again you can download all the code here.

I’ve created a very simple controller and hardcoded our JSON data to a $scope.albumData variable.

angular.module('thatcodecornerMusicApp')
  .controller('MainCtrl', function ($scope) {

    $scope.albumData = {
      'albums' :
        [
          {
            'name' : 'Thriller',
            'artist' : 'Micheal Jackson',
            'released' : '1982',
            'instock' : true
          },
          {
            'name' : 'The Dark Side of the Moon',
            'artist' : 'Pink Floyd',
            'released' : '1973',
            'instock' : true
          },
          {
            'name' : 'Bat Out of Hell',
            'artist' : 'Meat Loaf',
            'released' : '1977',
            'instock' : false
          },
          {
            'name' : 'Their Greatest Hits',
            'artist' : 'Eagles',
            'released' : '1976',
            'instock' : true
          }
        ]
    };

  });
<div class="albumDetail" ng-repeat="album in albumData.albums">
    <p>Name: {{album.name}}</p>
    <p>Artist: {{album.artist}}</p>
    <p>Released: {{album.released}}</p>
    <p>In Stock: {{album.instock}}</p>
    <hr>
</div>

Then I am using a built in angular directive called ngRepeat (written ng-repeat) to iterate over the list of objects inside the albumData.albums array and I’m creating a <p> element with the album details in it for each element inside the albumData.albums array.

Normalisation

First thing people notice is that when we write the directive in HTML it’s ng-repeat however in the official documentation it’s ngRepeat. The Angular developers refer to all directives by their normalised name (ngRepeat) however because HTML is case insensitive when refering to those directives inside the DOM we need to use lower-case dash-delimited format.

There are some other normalisation rules and you can read them all here. This will become important when we start to write our own directives.

One more directive

Lets say we want to hide all the Albums where we don’t have any stock, we can use another provided directive for that. We would do that by adding a ngShow to our div and binding that to our instock variable. Now when we iterate through the albums whenever the album.instock variable is true the album will be displayed and when it’s false the album won’t be displayed.

<div class="albumDetail" ng-repeat="album in albumData.albums" ng-show="album.instock">
  ...
</div>

So what have these directives done for us.

Firstly the ngRepeat updated the DOM to display our list of our albums. If our dataset changes the DOM will be automatically updated with the changes as well.

Secondly we were able to change the way things appeared based on some value inside our dataset.

Pretty powerful, and best of all we didn’t have to write tons of Javascript code to reach our desired goal, the directives which manipulate the DOM were all placed in the HTML and not in some obscure .js file in the project, or even worse mixed in with your business code.

AngularJS comes with a plethora of directives that will usually be enough to meet most requirement but sometimes we just might want to write own.

Writing our own directives

If we look at the code at the ‘3f5c27′ commit (use git log to find the commit and git checkout 3f5c27  to get your local repository to that version) we can see that the code we used to display the albums can be extracted into it’s own directive and then we will be able to reuse that directive whenever we need to display album data.

This is how we define our directive.

angular.module('thatcodecornerMusicApp')
  .directive('tccAlbumData', function () {
    return {
      restrict: 'E',
      scope: {
        album: '=data'
      },
      templateUrl: '../views/albumdata.html'
    };
  });

There is a lot going on above, so lets go through it step by step.

.directive('tccAlbumData', ...  defines the name of our directive however two important things to note here:

  1. Whenever you create your own directives it’s important that you give it a unique prefix (tcc in this case) so that there are no collisions when Angular starts compiling your directives. Also don’t prefix your directives with ng because that’s what the Angular guys use.
  2.  When we use the directive in HTML we will do it like this  <tcc-album-data data="album"></tcc-album-data>  remember we take the normalised name tccAlbumData and change it to dash-delimited format.

restrict: 'E', forces the directive to only be used as an element and not an attribute which would be denoted as   restrict: 'A', . The directives we used above (ng-show and ng-repeat) were used as attribute directives on the <div> tag. The general rule of thumb here is to use an element when creating a component that is in control of the template and to use attributes when we want to decorate an existing element with new functionality.

The next part of the code

scope: {
    album: '=data'
},

Allows us to pass data to the directive using the  data="album" attribute in our HTML. You can read more about Isolating the Scope of a Directive here. There is a little bit more to this so I encourage you to read the official documentation.

templateUrl: '../views/albumdata.html'  lastly we tell our directive which template to use. You can view the code for the albumdata.html here.

So with these simple steps we created our own directive which we can use whenever we want to display album data in our website in a standard way.

Final Words

You would have notice that I left  ng-show="album.instock"  still in the <div> on the main.html. It could be argued that I should have moved it to the directive template that would also be fine, I left it out of the directive template because we might want to display album data in other screens even if they are out of stock.

There are other aspects to directives but this post is getting pretty long so look for a part two soon.

Until next time may you be in your element.

-R

AngularJS Logo
AngularJS

A while back I wrote about Front End development and how picking the right technology or framework will affect the direction and success of our development projects. This time I am going to write about a specific framework AngularJS and how this brave little framework has changed the way front end development is being done.

What is AngularJS?

AngularJS is an open-source framework that is developed and maintained by Google (with large amounts of contribution from the community) it makes front end development easy by doing two things well.

  1. Angular forces the developer to use the Model View Controller architecture  (Angular also allows for Model View ViewModel, I want to write about the different architectures in a future blog)
  2. It handles data binding between Model and View in a really elegant way.

Angular Design Goals

Straight from the Angular wikipedia page:

AngularJS’s design goals include:

  • to decouple DOM manipulation from application logic. The difficulty of this is dramatically affected by the way the code is structured.
  • to decouple the client side of an application from the server side. This allows development work to progress in parallel, and allows for reuse of both sides.
  • to provide structure for the journey of building an application: from designing the UI, through writing the business logic, to testing.

Decoupling DOM manipulation from application logic results in smaller, easy to digest Javascript files. We all have a horror story of the two thousand line spaghetti .js file which everyone is afraid to touch. Taking all the DOM manipulation code out of the business logic code makes the code easier to read and easier to debug.

Decoupling the client side of an application from the server side means that the front end team can continue to develop and test and just mock out the services that are require. Then when the server side completes the services we just need to do some integration.

Providing structure. AngularJS helps developers focus on the piece of code they are currently writing. If we are busy writing a DOM manipulating directive then that’s all we need to focus on. Time to write some business logic? Great that goes in the controller so lets jump there and write that. How about some unit tests? Nice and easy because we didn’t mix up our DOM manipulation with our business code our tests can be written easier.

Extending HTML using directive

Directives are Angular’s way to help you develop web applications. Directives are what HTML would be like if HTML was designed with web applications in mind.

In essence directives are markers on DOM elements that let Angular attach specific behaviour to those elements, they even allow Angular to completely change how those elements look.

Some examples that we would use directives for:

Hiding a <div> element based on the value inside the “hideDiv” value.

<div ng-hide="hideDiv"></div>

Disable a button:

<button ng-disabled="disableSubmit">Submit</button>

And many more

Angular comes built in with directives that help us get started developing, it’s library of directives is pretty extensive. Angular has also made it really easy on us to write our own directives.

Some directives attach behaviour to elements while others change the entire element and how it looks. Directives deserve their own post (which is also coming soon). This will help you get started.

Two way data binding

Using some pretty cool magic Angular automatically synchronises data between model and views. So if for example we use the JSON object I wrote about last week:

{
"music-man" : { 
 "first-name" : "Bob",
 "last-name" : "Dylan",
 "age" : 74,
 "instruments" : ["Vocals", "Guitar", "Keyboards", "Harmonica"],
 "favouriteBeverage" : "probably Coffee"
 }
}

And we bound favouriteBeverage to an HTML input box like this:

<input type="text" ng-model="$scope.music-man.favouriteBeverage" />

If the model was somehow updated (maybe via a method call) the text inside the input box would be updated. Also if the text inside the input box is updated then the music-man’s favouriteBeverage value inside the JSON object would also be updated.

This form of data binding is a boon for people who have worked with Javascript back in the day. A lot of your effort was invested into writing code that would update the view based on model changes and vice versa. Which is no longer needed.

Active community

Angular is maintained and developed by Google, however it has a really active community. In fact as part of the ng-conf which is a community run conference on Angular, in the Keynote Brad Green and Igor Minar (the guys at Google who run the Angular project) dedicated a large portion of their talk to thanking the really active community.

In the last month the Angular team has managed to do 107 pulls on their GitHub account (stats here).

Excluding merges, 48 authors have pushed 472 commits to master and 891 commits to all branches. On master, 1,092 files have changed and there have been 62,439 additions and 49,525 deletions.

 

There is a lot more to Angular and I will be covering some of it as the weeks go by.

Until next time, may things that were difficult become easy for you.

-R