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
.
<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:
$injected
as needed.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:
<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>
As you might notice we have new friends: ng-controller
, ng-repeat
and $scope
.
$injected
as needed.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.
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 },
];
}]);
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:
<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="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.25/angular-route.min.js"></script>
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'
});
}]);
$injected
as needed.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:
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
.
This is what is happening:
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:
$injected
as needed.Note you can also chain many filters and also define your own filters.
HTML enhanced for web apps!
<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 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…:
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 #express #mongodb #javascript