This tutorial is meant to be as clear as possible. At the same time, we are going to cover the concepts that you will need most of the time. All the good stuff without the fat :)
MEAN Stack tutorial series:
We are going to start building all the examples in a single HTML file! It embedded JavaScript and NO styles/CSS for simplicity. Don’t worry, in the next tutorials, we will learn how to split use Angular modules. We are going to break down the code, add testing to it and styles.
Angular.js is a MVW (Model-View-Whatever) open-source JavaScript web framework that facilitates the creation of single-page applications (SPA) and data-driven apps.
TL; DR: AngularJS is awesome for building testable single page applications (SPA). Also, excel with data-driven and CRUD apps. Show me the code!.
AngularJS motto is
HTML enhanced for web apps!
It extends standard HTML tags and properties to bind events and data into it using JavaScript. It has a different approach to other libraries. jQuery, Backbone.Js, Ember.js and similar… they are more leaned towards “Unobtrusive JavaScript”.
Traditional JavaScript frameworks, use IDs and classes in the elements. That gives the advantage of separating structure (HTML) from behavior (Javascript). Yet, it does not do any better on code complexity and readability. Angular instead declares the event handlers right in the element that they act upon.
Times have changed since then. Let’s examine how AngularJS tries to ease code complexity and readability:
$injected
as needed.Without further ado, let’s dive in!
AngularJS has an extensive API and components. In this tutorial we are going to focus on the most important ones, such as directives, modules, services, controllers and related concepts.
The first concept you need to know about AngularJS is what are directives.
Directives are extensions of HTML markups. They could take the form of attributes, element names, CSS class and or even HTML comments. When the AngularJS framework is loaded, everything inside ng-app
it’s compiled. The directives are bound to data, events, and DOM transformations.
Notice in the following example that there are two directives: ng-app and ng-model.
Notice in the following example that there are two directives: ng-app
and ng-model
.
Hello World in AngularJS
<html ng-app>
<head>
<title>Hello World in AngularJS</title>
</head>
<body>
<input ng-model="name"> Hello {{ name }}
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.25/angular.min.js"></script>
</body>
</html>
We going to learn about some of the main built-in directives as we go:
<html>
or <body>
.input
, select
, checkboxes
, textarea
. They keep data (model) and visual elements (HTML) in sync.{{ }}
are a way of binding models to elements in HTML. In the example above, the ng-model
name is bound to the placeholder {{ name }}
. Play with the example below to see how the placeholder is updated real-time to whatever you type in the textbox.Data binding AngularJS example:
You can create your own directives. Checkout the this tutorial for more: creating-custom-angularjs-directives-for-beginners. It will go deeper into directives.
Data binding is an AngularJS feature that synchronizes your model data with your HTML. That’s great because models are the “single source of truth”. You do not have to worry about updating them. Here’s a graph from docs.angularjs.org.
Whenever the HTML is changed, the model gets updated. Wherever the model gets updated it is reflected in HTML.
$scope
it is an object that contains all the data to which HTML is bound. They are the glue your javascript code (controllers) and the view (HTML). Everything that is attached to the $scope
, it is $watch
ed by AngularJS and updated.
Scopes can be bound to javascript functions. Also, you could have more than one $scope
and inherit from outer ones. More on this, in the controller’s section.
Angular.js controllers are code that “controls” certain sections containing DOM elements. They encapsulate the behavior, callbacks and glue $scope
models with views. Let’s see an example to drive the concept home:
AngularJS Controller Example
<body ng-controller="TodoController">
<ul>
<li ng-repeat="todo in todos">
<input type="checkbox" ng-model="todo.completed">
{% raw %}{{ todo.name }}{% endraw %}
</li>
</ul>
<script>
function TodoController($scope){
$scope.todos = [
{ name: 'Master HTML/CSS/Javascript', completed: true },
{ name: 'Learn AngularJS', completed: false },
{ name: 'Build NodeJS backend', completed: false },
{ name: 'Get started with ExpressJS', completed: false },
{ name: 'Setup MongoDB database', completed: false },
{ name: 'Be awesome!', completed: false },
]
}
</script>
</body>
AngularJS controller interactive example:
As you might notice we have new friends: ng-controller
, ng-repeat
and $scope
.
<strong>ng-controller</strong>
is a directive that tells angular what function controller to use for a particular view. Every time AngularJS loads, it reads the ng-controller
argument (in this case “TodoController”). Then, it will look for a function in plain old javascript object (POJO) with the same name or for angular.controller
matching name.<strong>$scope</strong>
As mentioned earlier $scope
‘s are the glue between the data models in the controllers and the views. Take a look to our “TodoController” it has a parameter named $scope
. AngularJS is going to pass ($inject
) that parameter, and whatever you attach to it, it will be available in the view. In this example is the particular is the todos
array of objects.<strong>ng-repeat</strong>
as its name implies, it is going to “repeat” the element and sub-elements where this directive is declared. It is going to iterate for each element in the $scope.todos
array.<strong>ng-model</strong>
notice that the checkbox is bound to the todo.completed
. If todo.completed
is true, then the checkbox is going to be checked and vice versa.Modules are a way to encapsulate different parts of your application. They allow reusing code in other places. Here’s an example of how to rewrite our controller using modules.
AngularJS Module Example
angular.module('app', [])
.controller('TodoController', ['$scope', function ($scope) {
$scope.todos = [
{ title: 'Learn Javascript', completed: true },
{ title: 'Learn Angular.js', completed: false },
{ title: 'Love this tutorial', completed: true },
{ title: 'Learn Javascript design patterns', completed: false },
{ title: 'Build Node.js backend', completed: false },
];
}]);
Notice the <html ng-app="app">
in the example below
Using modules brings many advantages. They can be loaded in any order, and parallel dependency loading. Also, tests can only load the required modules and keep it fast, clear view of the dependencies.
Templates contain HTML and Angular elements (directives, markup, filters or form controls). They can be cached and referenced by an id.
Here’s an example:
AngularJS Template Example
<script type="text/ng-template" id="/todos.html">
<ul>
<li ng-repeat="todo in todos">
<input type="checkbox" ng-model="todo.completed">
{{ todo.name }}
</li>
</ul>
</script>
Does the code inside looks familiar? ;)
Notice they are inside the script
and has a type of text/ng-template
.
ngRoutes module allows changing what we see in the app depending on the URL (route). It, usually, uses templates to inject the HTML into the app.
It does not come with AngularJS core module, so we have to list it as a dependency. We are going to get it from Google CDN:
<script src="<a href="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.25/angular-route.min.js"></script>" target="_blank">https://ajax.googleapis.com/ajax/libs/angularjs/1.2.25/angular-route.min.js"></script></a>
NEW FEATURE: add notes to the todo tasks. Let’s start with the routes!
angular.module('app', ['ngRoute'])
.config(['$routeProvider', function ($routeProvider) {
$routeProvider
.when('/', {
templateUrl: '/todos.html',
controller: 'TodoController'
});
}]);
ng-controller="TodoController"
from the body tag. The controllers are now called based on the route.ngView
is a directive used by $routeProvider
to render HTML into it. Every time the URL changes, it will inject a new HTML template and controller into ngView.Notice that if you want to create a 2nd controller and share $scope.todos it is not possible right now. That is when services become handy. Services are a way to inject data dependencies into controllers. They are created through factories. Let’s see it in action:
AngularJS Service Factory Example
angular.module('app', ['ngRoute'])
.factory('Todos', function(){
return [
{ name: 'AngularJS Directives', completed: true },
{ name: 'Data binding', completed: true },
{ name: '$scope', completed: true },
{ name: 'Controllers and Modules', completed: true },
{ name: 'Templates and routes', completed: true },
{ name: 'Filters and Services', completed: false },
{ name: 'Get started with Node/ExpressJS', completed: false },
{ name: 'Setup MongoDB database', completed: false },
{ name: 'Be awesome!', completed: false },
];
})
.controller('TodoController', ['$scope', 'Todos', function ($scope, Todos) {
$scope.todos = Todos;
}])
We are now injecting the data dependency Todo
into the controllers. This way we could reuse the data to any controller or module that we need to. This is not only used for static data like the array. But we could also do server calls using $http
or even RESTful $resource
.
Let’s say we want to show the details of the task when we click on it. For that, we need to create a 2nd controller, template, and route that uses this service:
(NOTE: Click on the links and it will take you to the todo details. Use backspace key to go back to the main menu)
This is what is happening:
HTML
tab, we created a second template /todoDetails.html
which contains the todo details we want to show./todos.html
we want to have a link that points to the todo
detail. We are using the $index
which is the corresponding order number in a ng-repeat
.JS
tab, we created a new $routeProvider
. It points to a new controller TodoDetailCtrl
and the template that we created on #1. The :id
parameter it is accessible in the controllers through $routeParams
.TodoDetailCtrl
. Also, we injected the dependencies which are $scope
, Todos
(factory), and $routeParams
which will have the id
param.$scope
in the new controller. Instead of using the whole array, we are going to select only the one that we need using the id
that we set in step #2.NOTE: in codepen, you will not see the URL. If you want to see it changing, you can download the whole example an open it from here.
Filters allow you to format and transform data. They change the output of expressions inside the curly braces. AngularJS comes with a bunch of useful filters.
Built-in Filters:
Note you can also chain many filters and also define your own filters.
NEW FEATURE: Search todo tasks by name. Let’s use a filter to solve that problem.
<script type="text/ng-template" id="/todos.html">
Search: <input type="text" ng-model="search.name">
<ul>
<li ng-repeat="todo in todos | filter: search">
<input type="checkbox" ng-model="todo.completed">
<a href="#/{{$index}}">{{todo.name}}</a>
</li>
</ul>
</script>
Notice that we are using search.name
in the ng-model
for search. That will limit the search to the name
attribute and search.notes
will look inside the notes only. Guest what search
would do then? Precisely! It searches in all the attributes. Fork the following example and try it out:
Congrats! You have completed part 1 of this 3 part series. We are going to build upon the things learned in here, in the next post we are going to setup a backend in NodeJS and MongoDB and connect it to AngularJS to provide a full featured CRUD app. Continue with:
I also have created BackboneJS tutorials check it out:
Congrats, you have reached this far! It is time to test what you have learned. Test-Driven Learning (TDL) ;). Here’s the challenge: open this file on your favorite code editor. Copy the boilerplate code and built the full app that we just build in the previous examples. Of course, you can take a peek from time to time if you get stuck ;)
Download this file as…:
-OR-
Fork and edit online:
This is the full solution and you can see it live in here.
<html ng-app="app">
<head>
<title>ngTodo</title>
</head>
<body>
<ng-view></ng-view>
<!-- Libraries -->
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.25/angular.min.js"></script>
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.25/angular-route.min.js"></script>
<!-- Template -->
<script type="text/ng-template" id="/todos.html">
Search: <input type="text" ng-model="search.name">
<ul>
<li ng-repeat="todo in todos | filter: search">
<input type="checkbox" ng-model="todo.completed">
<a href="#/{{$index}}">{{todo.name}}</a>
</li>
</ul>
</script>
<script type="text/ng-template" id="/todoDetails.html">
<h1>{{ todo.name }}</h1>
completed: <input type="checkbox" ng-model="todo.completed">
note: <textarea>{{ todo.note }}</textarea>
</script>
<script>
angular.module('app', ['ngRoute'])
//---------------
// Services
//---------------
.factory('Todos', function(){
return [
{ name: 'AngularJS Directives', completed: true, note: 'add notes...' },
{ name: 'Data binding', completed: true, note: 'add notes...' },
{ name: '$scope', completed: true, note: 'add notes...' },
{ name: 'Controllers and Modules', completed: true, note: 'add notes...' },
{ name: 'Templates and routes', completed: true, note: 'add notes...' },
{ name: 'Filters and Services', completed: false, note: 'add notes...' },
{ name: 'Get started with Node/ExpressJS', completed: false, note: 'add notes...' },
{ name: 'Setup MongoDB database', completed: false, note: 'add notes...' },
{ name: 'Be awesome!', completed: false, note: 'add notes...' },
];
})
//---------------
// Controllers
//---------------
.controller('TodoController', ['$scope', 'Todos', function ($scope, Todos) {
$scope.todos = Todos;
}])
.controller('TodoDetailCtrl', ['$scope', '$routeParams', 'Todos', function ($scope, $routeParams, Todos) {
$scope.todo = Todos[$routeParams.id];
}])
//---------------
// Routes
//---------------
.config(['$routeProvider', function ($routeProvider) {
$routeProvider
.when('/', {
templateUrl: '/todos.html',
controller: 'TodoController'
})
.when('/:id', {
templateUrl: '/todoDetails.html',
controller: 'TodoDetailCtrl'
});
}]);
</script>
</body>
</html>
#angular.js #node-js #mongodb