Tuesday, October 23, 2012

Angular JS - The Very Basics

As I'm all about Angular JS these days, and the four friends I have that read this blog have told me to do a blog entry about it, I figured I would finally write a blog entry about the basics of Angular JS.

What is Angular?

It's a JavaScript framework from Google that encompasses:
  • Two way binding
  • Dependency injection
  • Built-in handling of RESTful services
  • Handling of AJAX calls
  • Handling of hash-based routing (for single page applications)
  • Templating
  • Reusable controls
So... essentially it does everything that Knockout and Backbone do, and then some.

So enough of that, let's get to some code.

Here is the basic code required to do something simple. In this case, I've made a little "Hello World" app that allows the user to reverse the name with a click.

/* Declare your main module.
 * this is your angular application module*/
var app = angular.module('myApp', []);

/* register a controller */
app.controller('MainCtrl', function($scope) {
  /* $scope is what is used for two-way binding */
  $scope.name = 'World';
  /* declare a method to call from a click in our markup */
  $scope.reverseName = function () {
    $scope.name = $scope.name.split('').reverse().join('');

And here's the markup required:

<!doctype html>
<html ng-app="myApp" >
  <script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.0.2/angular.js"></script>
  <script src="app.js"></script>
<body ng-controller="MainCtrl">
    <input type="text" ng-model="name"/>
    <button ng-click="reverseName()">Reverse</button>
  Hello {{name}}!

Here's a demo to try that out. (I used Plnkr for this, I recommend Plnkr for playing with Angular over JSFiddle because it works a little better for Angular)

Pretty straight forward, I think. That sums up the basics, really. The VERY basic basics. I'll be showing a lot more features as time goes on, but this is a good starting point I think.

Fears of Angular's "Custom HTML Tags"

One of the primary complaints I read online from developers that really don't understand angular is over it's use of "non-standard HTML" for directives. I'll address that a little more when I post about directives and reusable controls, but I wanted to make it a point to say something in my first post about Angular on the matter: Angular actually only uses "non-standard" HTML tags as placeholders. Those placeholders are in fact replaced by Angular with standard HTML tags (presuming the author of the Angular app in question is writing valid HTML). More on that to come, but it's really not as scary as it looks, and it's so powerful, it's definitely worth a look.

No comments:

Post a Comment

This form allows some basic HTML. It will only create links if you wrap the URL in an anchor tag (Sorry, it's the Blogger default)