AngularJS is a front end framework that applies the Model-View-Controller (MVC) architecture to front end development. Angular is used for making Single Page Applications (SPA), meaning that instead of calling back to the server to load up a new page we simply switch out the html template we are displaying to the user. This is done all in the browser by using Angular’s routing on the client instead of doing the routing on the server. Single Page Applications result in faster web sites that never have to load up or refresh pages, creating a more responsive user experience.

AngularJS is also a templating engine in that it allows you to display data by injecting it straight from the JavaScript code into the HTML by use of the double curly braces syntax, {{ }}. Angular connects HTML to JavaScript by by declaring an Angular Module in your HTML and JavaScript files. You then put your website’s Front-End logic inside methods of that angular module. The module is the place where you put all your Angular code. AngularJS has two-way binding, meaning that changes the user makes to inputs on the website will automatically and instantaneously be transmitted to Angular’s model and any changes made to that data in the model can be instantly reflected back in the view. Controllers are used to handle user events in the browser and affect changes in the Model and View.

Angular uses the concept of directives to link the View and Controller together. Directives are Angular attributes added to elements in the DOM which link to Angular’s Model, thereby creating two-way binding. Now let’s quickly go over the MVC concept in Angular.

Model

The Model is the data store of the application, in this case just for the front end. It stores data that will be output to the user in the View. The way to do this is by using Angular’s built-in $scope object. Angular uses two-way data binding so you pass data not just from the JavaScript code to the HTML but also from HTML to the JavaScript, and this is all done automatically thanks to Angular.

View

The View refers to what is displayed to the user, specifically the HTML templates that combine both HTML code and Angular directives used to interact with the JavaScript code base.

Controller

The Controller holds the logic you code in JavaScript to handle the interactions between events the user creates in the browser and the logic used to handle those actions, whether that be changing data in the Model or changing the View. Essentially the Controller connects the View and Model together.

Setting Up Angular

Start by making a new directory on your computer for this project. Inside that directory make an index.html file and a main.js file. Fill out the boilerplate HTML code:

<!DOCTYPE html>

<html>

<head>

<title> Angular Practice </title>

</head>

<body>

</body>

</html>

To run our code in the browser go into the terminal and into the directory for this project and run the python web server on port 8000 with the following command, and view it in the browser with localhost:8000 as the URL.

python -m SimpleHTTPServer

It is really easy to add Angular to a project. Just grab the Angular CDN from somewhere, like from the Google Hosted Libraries, and put it in your HTML file just before the closing head tag. You can also include Angular in your project with a bower install, but here we’ll just use the CDN. We will also include our main.js file just before the closing body tag. Note that the line that loads Angular must always come before loading any JavaScript files that use Angular or else the files will not run. Here main.js is loaded after AngularJS so we are fine.

<!DOCTYPE html>

<html>

<head>

<title> Angular Practice </title>

<script src='https://ajax.googleapis.com/ajax/libs/angularjs/1.3.14/angular.min.js'></script>

</head>

<body> <script src='main.js'></script>

</body>

</html>

To use the most basic funtionality of Angular all we need to do is initialize our website as an Angular app using the ng-app directive.We will connect our HTML to the AngularJS part of our app by putting ng-app inside the opening body tag (or the opening html tag, it doesn’t matter). Angular directives are basically attributes added to elements in the DOM which attach behaviors to that element. Note that all Angular directives begin with “ng-“. The opening body tag should now look like this:

<body ng-app>

Now we are ready to start seeing how Angular can evaluate expressions inside our HTML code. Angular uses double curly braces to include data from AngularJS in the HTML and evaulate expressions. But we can also do math with it. So {{ 4 + 5 }} will display 9 in the browser. Try it out for yourself, put {{ 4 + 5 }} anywhere inside the body of your document.

{{ 4 + 5 }}

Creating a Controller

Doing math in the HTML is fine and all, but let’s actually start to use Angular code now. To do this we need to do three things. First we need to give our Angular app a name by setting our ng-app directive equal to some string. Then we need to add in an ng-controller directive and give it a name. Finally we need to create our Angular module and controller in JavaScript inside our main.js file. As explained above, a controller is a set of logic in JavaScript that interacts with the View to react to any desired interaction from the user and display any desired changes back to the View and the user, while also acting as the middleman for storing data on the Front End or sending it to the server. Let’s change our HTML file so that our ng-app has a name as well as add in the ng-controller directive. The opening body tag will now look like this:

<body ng-app='learningAngular' ng-controller='practiceCtrl'>

Our Angular module and controller have now be initialized to the entire body of our HTML document. Now let’s create the module and controller in our main.js file:

angular.module('learningAngular', []) .controller('practiceCtrl', ['$scope', function($scope) {



}]);

We’ve done a few things here in just two lines of code. In the first line of code we created our Angular module with the name ‘learningAngular’. The empty array which we used as the second argument for the module() method is for a list of dependencies that this module relies on. It takes a list a strings that are the names of other Angular modules that will be used in this module. But since we won’t be using any other modules here we just give it an empty array. Note that you can use an Angular module across many files, but you only put in the dependencies array in one JavaScript file — to create the module. The dependencies array initializes our module. In all other files that use the module you would access the it with the same line of code but without that dependencies array, so the module() method would only take one argument which is the name of the module.

The second line of code creates our controller. Notice that we did not end the first line with a semi-colon because controller() is a method we are calling on the module. So this second line is really just a continuation of the first line by chaining the controller() method onto angular.module(). We give it the name of the ng-controller we used in our HTML file so that Angular can connect the two together. We then put all of the Angular services we will be using in these controllers as string elements in an array, and the last element is the function in which we will put all our controller logic. Services in Angular are objects with built-in functionality that are used as tools. They always start with a ‘$’, and to use them we always have to inject them into the controller as shown below. In this article we are only using the $scope service, which is basically Angular’s Model object. It is used to store data within the controller that can be automatically accessed in the View through the process mentioned above called two-way data binding. When you bind something to the $scope object in the View it can be immediately accessed in the controller. When you change a property of the $scope object in the controller it will be immediately reflected to the user in the View.

Note that the reason we declare things in an array inside the controller() method is because Angular requires this for uglification. Uglification is the process of simplyifying variable names in production so that the code files are compressed when an app or website is shipped for consumer use. This means that variable names get changed, but Angular has specific names for its services like $scope so when the code gets uglified these names change and Angular won’t work. In order to fix this you put the list of services to be injected into the controller as strings in an array as shown above, with the function for the controller as the last element in the list. Strings don’t get changed in the uglification process, so Angular is able to associate each uglified argument in the function with its actual name in the list of strings. Angular just pairs them up in the order they come in, so it is crucial to put the services into the function’s argument list in the same order that you put their string names. It is good practice to ready Angular for ulgification so we will use the code above, but if you aren’t uglifying the code then you don’t need that array and you can create the controller like this:

.controller('practiceCtrl', function($scope) {



});

Using $scope and Two-Way Data Binding

Let’s see how this $scope service is used. We’ll add a property to it and display it in the View. In the controller add this code:

$scope.name = 'Josephine';

Now in our View, index.html, we will put {{ name }} and magically see Josephine appear in the browser as Angular automatically pulls in $scope.name from our controller. In Angular we reference properties of $scope by putting just the property name between double curly braces in the view. Inside of the body of our index.html will now look like this (added <br> tags to keep stuff on different lines in the browser).

{{ 4 + 5 }} <br>

{{ name }} <br>

We have seen one-way binding from Controller-to-View. Now let’s see two-way binding from View-to-Controller and automatically binded back from Controller-to-View. To do this we’ll put a textbox into our HTML and add the ng-model directive to it which creates a property on $scope whose key is what you set ng-model equal to and whose value is whatever value the user puts into the input field. Let’s see this in action, add this code to index.html:

<input type='text' ng-model='name'> <br>

When you refresh your browser something a little magical happens. The name we assigned to $scope.name shows up in the input field. This is because ng-model=’name’ associates the value of the input field with $scope.name, whether or not we have previously created $scope.name in the controller, ng-model create it for us. Since we already created $scope.name and assigned it a value the ng-model brings that value into our textbox!

Now to see the two-way data binding in action change the value in the textbox. You’ll see that the value printed out by {{ name }} changes to match the textbox value! This is two-way data binding. We change something in the view, specifically the value in the textbox, that change is brought to the controller because the textbox is binded to $scope.name through ng-model, and the new value of $scope.name is brought back to the View where we have {{ name }}. This is very powerful and results in changing what the user sees automatically and instantaneously through Angular without having to write any JavaScript logic, such as you would have to do if we were using jQuery or plain JavaScript.

The ng-model directive is only used for inputs, specifically the input, select, and textarea tags. To have this sort of binding with any other DOM element we use the ng-bind directive. To see that in action we’ll add a div tag with ng-bind=’name’ and the content inside the div will change to match what we put in the textbox because they will both be bound to $scope.name.

<div ng-bind='name'><div>

Now that you know how two-way data binding works lets explore a few more Angular directives so that you have the basics of Angular Controller-View interaction under your belts. We will go over:

ng-click

ng-show

ng-hide

ng-repeat

ng-click

The ng-click directive is Angular’s way of handling click events. To use it you make a function call as the value given to ng-click. Since ng-click is an attribute on a DOM element the function call must be wrapped up in quotes. The function we are calling must be defined as a property of the $scope object back in the controller. Let’s first create our button in index.html and have its click functionality be handled by a function called alertMe().

<button ng-click='alertMe()'>Alert Me Angular</button>

Now in our controller we’ll add a function on the $scope object called alertMe that will be called when you click the button in the browser. Make this function, then click the button in the browser to see ng-click in action.

$scope.alertMe = function() {

alert('Congrats! You used ng-click!');

};

ng-show

The ng-show directive is Angular’s way of hiding or showing content. We put the directive in a DOM element and give it an expression to evaluate. If that expression evaluates to true then that element and anything inside it will show. If it evaulates to false then Angular automatically adds an .ng-hide class to the element. The .ng-hide class is how Angular hides DOM elements. Let’s create a div with some content and the ng-show directive and have it evaulate a variable called willShow.

<div ng-show='willShow'> Angular is showing this! </div>

Now we need to create that ‘willShow’ variable as a property of $scope so that Angular can evaluate it. If we don’t initialize $scope.willShow in the controller then when Angular evaluates it on the ng-show directive its value will be undefined which evaluates to false so the element will not show.

$scope.willShow = true;

Our div element will be shown because willShow equals true. Let’s quickly add a button to toggle on and off the showing of this div. In the view and in the controller add these two pieces of code, respectively:

<button ng-click='toggleDiv()'> Toggle Div </button> $scope.toggleDiv = function() {

$scope.willShow = !$scope.willShow;

};

The toggle button either removes or adds that div from the HTML depending on whether or not it is already there!

ng-hide

The ng-hide directive is just like ng-show except the exact opposite. This can be used when you want to use one expression to show an element with ng-show and the same expression to hide an element with ng-hide. So let’s make another div element that will be hidden when $scope.willShow equals true. Our toggle button will then toggle both divs but in opposite ways. We just need to add one line of code to index.html to accomplish this:

<div ng-hide='willShow'> Using ng-hide! </div>

The complete HTML code for using ng-show and ng-hide should look like this:

<button ng-click='toggleDiv()'> Toggle Div </button>

<div ng-show='willShow'> Angular is showing this! </div>

<div ng-hide='willShow'> Using ng-hide! </div> <br>

ng-repeat

The final directive we will work with here is ng-repeat, which allows us to iterate over an array or hash on the $scope object and display each of their elements in the browser. We’ll start by creating both an array and a hash (object) on $scope in the controller:

$scope.puppies = ['Rex', 'Fido', 'Rover', 'Archie'];

$scope.classGrades = {

Max: 'A',

Joan: 'B+',

Jay: 'A-',

Charlie: 'C'

};

Now we can loop over both these $scope properties and print out their contents in the browser by using the ng-repeat directive on elements in our View. In the case of the array we will just print out each element of the array, but for our classGrades object we will print out both the keys and the values. We’ll display both of these collections in unordered lists.

<ul ng-repeat='puppy in puppies'>

<li> {{ puppy }} </li>

<ul> <ul ng-repeat='(student, grade) in classGrades'>

<li> {{ student }}, {{ grade }} </li>

<ul>

In our puppies list we give ng-repeat ‘puppy in puppies’, ‘puppies’ being the name of our array on $scope and ‘puppy’ referring to the value of each element in the array. So all we have to do is put {{ puppy }} inside a list item tag to display each puppy name in the puppies array.

We can do the same thing to loop through our classGrades object and just display the grades, but in this case I also want to display the keys of the object too, which are the names of the students. This is done with the following sytnax:

ng-repeat=’(key, value) in objectName’

So we are defining inside our ng-repeat that ‘student’ refers to each key and ‘grade’ refers to each value as we loop through the classGrades object. We just then put them each inside double curly braces to evaluate ‘student’ and ‘grade’ to the keys and values of the object. It’s as simple as that!

Summary

This is part one of a three part series on learning Angular and building a to-do list in Angular. We covered what Angular is and what it is used for, how to get started with it using the ng-app and ng-controller directives, how to make the Angular module and controller in JavaScript, how to use $scope and two-way data binding with ng-model and ng-bind, as well as the following Angular directives: ng-click, ng-show, ng-hide, and ng-repeat.

Go here to get the full code from this tutorial.

Part 2 in this series will cover how to do Front End routing in Angular to make Single Page Applications by using the Angular UI Router. It will also touch on a couple of new Angular services including how to make AJAX calls using $http.

Part 3 will use what you’ve learned in the first two articles, plus learning a few new things, to create a to-do list using Angular.

For documentation on Angular check out the Official Angular Developer Guide and the Official Angular API Reference.

Thanks for reading! Continue on with Part 2: Routing!