Click here to Skip to main content
65,938 articles
CodeProject is changing. Read more.
Articles / AngularJs

Blind Date with AngularJS

5.00/5 (2 votes)
29 Apr 2016CPOL5 min read 8.8K  
Blind date with AngularJS

Are you starting to work on a new application that is using AngularJS? You have heard of it before and would like to know more about it? And have no idea where to start? You are in luck! Continue reading this blog and start learning this hot thing called Angular!

AngularJS is a JavaScript MVC framework that has some compelling features for not only developers, but designers as well! It is great for building complex client-side applications. In this blog, I will talk about the most essential features and how they can help make your next web app awesome.

MVC

The Model-View-Controller pattern means a lot of different things to different people. AngularJS does not implement MVC in the traditional sense, but rather something closer to M-V-VM (Model-View-ViewModel).

The model is simply the data in the application (JavaScript objects). There is no need to inherit from framework classes, etc. The fact that we are dealing with vanilla JavaScript is a really nice feature, which cuts down on the application boilerplate.

The view is the HTML that exists after AngularJS has parsed and compiled the HTML to include rendered markup and bindings. The $scope has a reference to the data, the controller defines behavior, and the view handles the layout.

A viewmodel is that $scope object that lives in the application, which is pretty much the center of any Angular code. It provides specific data and methods to maintain specific views. It is just a simple JS object with a small API which was designed with any changes to its state.

Let’s Take This Thing Apart!

Now I would like to break the whole thing down and share my thought process on how I look at Angular. I look at this whole process as a person (me) putting books on the bookshelf. My hands are ultimately the JS code, the brains behind the whole operation. And the books are the objects.

The bookshelf is going to represent the HTML code that we write according to our needs. It can be 10-20 feet tall, 5-10 feet wide, contain 5, 10 or even 20 shelves, and be green, blue, or whatever color you want it to be. This is where Angular’s ng-directives, data binding and expressions come to play.

Expressions

JavaScript
<div>Sum of 1+1 is: {{1+1}} </div>

One of the first things a developer writes in Angular, other than the ng-app directive, is an expression. This is easily identified as the code written inside of a binding {{ }} or directive.

Back to our bookshelf. Expressions will help you title the books on the shelf. So if you have an object called ‘book’ with properties like ‘author’ and ‘title’, you can populate a div just like this:

JavaScript
<div id="shelfNumber3">{{book.author}}, {{book.title}}</div>

Ng-directives

Directives are the most important components of any AngularJS application. It is something that introduces new syntax. Directives are markers on a DOM element which attach a special behavior to it.

For example, static HTML does not know how to create and display a date picker widget. To teach HTML this new syntax, we need a directive. The directive will somehow create an element that behaves like a date picker. We will see how this is achieved subsequently.

If you have written an Angular application before, then you have used directives, whether you realized it or not. You might have used simple directives like ng-model, ng-repeat, ng-show, etc.

All these directives attach special behavior to DOM elements. For example, ng-repeat repeats a specific element and ng-show conditionally shows an element. If you want to make an element draggable/droppable, then you might create a directive for that too.

The basic idea behind a directive is very simple. It makes your HTML truly interactive by attaching event listeners to the elements and/or transforming the DOM.

Data Binding

Data binding is the most useful and powerful feature among any of the existing or upcoming software development technologies. It is actually a process that bridges a connection between the view and business logic of the application.

AngularJS provides some predefined data binding directives which are as follows:

  • ng-bind – Binds the inner Text property of an HTML element.
  • ng-bind-template – Almost similar to the ng-bind directive but allows for multiple templates.
  • ng-non-bindable – Declares a region of content for which data binding will be skipped.
  • ng-bind-html – Creates data bindings using the inner HTML property of an HTML element.
  • ng-model – Creates a two-way data binding.

Controllers

Controllers are nothing but plain JavaScript functions. The role of controllers in Angular is to expose data to our view via $scope and to add functions to $scope that contain business logic to enhance view behavior. Presentation logic should remain within views and directives.

Services

A service provides us a method to keep data across the lifetime of the angular app. It is used to organize and share data and functions across the application.

Let’s Create A Simple Web App Using AngularJS!

JavaScript

JavaScript
var logger = require('./../service/Logger')('BookshelfCtrl');

module.exports = ['$scope', 'Ajax', function ($scope, Ajax) {
    'use strict';

       var handlers = {
            error: function () {
                var args = Array.prototype.slice.call(arguments);
                logger.error(args);
                $scope.serverError = arguments[0].message;
            },
            success: function (resp) {
                var args = Array.prototype.slice.call(arguments);
                logger.log(args);
                $scope.allBookshelves = resp.bookshelves;
            }
        };
        Ajax.getAllBooks(handlers.success, handlers.error);
}];

HTML

HTML
<body>
<div id="bookShelf>
<div data-ng-repeat="bookshelf in allBookshelves" 
id="shelfNumber{{$index}}">
      <span id="bookNumber{{$index}}", 
      data-ng-repeat="book in bookshelf.books">{{book.title}}, 
      {{book.author}}</span>
</div>
</div>
</body>

JSON Object That We Get

JavaScript
{
	"bookshelves": {
		"1": [{
			"BookOne": [{
				"title":"Harry Potter and the Philosopher's Stone",
				"author": "J.K.Rowling"
			}],
			"BookTwo": [{
			"title":"Harry Potter and the Chamber of Secrets",
			"author":"J.K.Rowling"
                        }]
	}],
	"2": [{
		"BookOne": [{
				"title":"Harry Potter and the Prisoner of Azkaban",
				"author":"J.K.Rowling "}
			],
			"BookTwo": [{
			   "title": "Harry Potter and the Goblet of Fire",
		  	"author": "J.K.Rowling"
		}
	]
}]
}

Conclusion

As you can see, Angular makes it pretty simple to get a hold of data and populate it into the spots that we need. HTML page gets set up, controllers start up, functions get triggered, calls are made through services, and data is returned goes back to controller functions and is spread throughout HTML using ng-directives. All in all, Angular is a great, useful tool to build modern, good looking SPAs.

I hope you found this helpful, but this is just scratching the surface of AngularJS’s capabilities. If you would like to learn more about Angular, search our company blog, or wait for my next one. ??

License

This article, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)