Why Angular?
Angular includes a wealth of essential features such as mobile gestures, animations, filtering, routing, data binding, security, internationalization, and beautiful UI components. It's extremely modular, lightweight, and easy to learn.
It is fully extensible and works well with other libraries. Every feature can be modified or replaced to suit your unique development workflow and feature needs
AngularJS Features
Getting started
Views, Controllers and Scope
Directives, Filters
Services and Routes
What's new in Angular 2
Angular works by separating application logic from data on the client-side.
Controllers, Services and Models are used to glue all the logic and data operations together.
data and logic are separated so this means that your data (the dynamic stuff), your HTML templates (the static stuff), and your logic (the controllers and binding markup) work together to make the application work.
My aim is to show you how everything fit together. Hopefully by the end of this you will know what to use for what purpose and where to find it.
ng-app
JSFiddle
Just adding ng-app directive anywhere in your html creates the most basic angular app. Now you can start using data bindings and templating that comes with angular.
Modules
var myApp = angular.module("demoApp", ['ngMaterial']);
myApp.controller(...);
myApp.directive(...);
Modules are used to fully encapsulate all the angular code of your application into one entry point.
This code here will create a global module called demoApp and assign it to the myApp variable. I have also included ngMaterial module in my definition array, ['ngMaterial']. Definition array defines all the other modules and dependencies that must be loaded prior to this module being activated.
The myApp variable is accessible throughout your application and you can use it to define your directives, controllers and other modules.
Controllers
Set up the initial state of the $scope object.
Add behavior to the $scope object.
app.controller("MainController", function($scope){
$scope.meaningOfLife = 42;
$scope.changeMeaning = function(newMeaning){
$scope.meaning = "The meaning of life is " + newMeaning;
};
})
Angular Directives extends DOM behavior.
Directives let you invent new HTML syntax, specific to your application.
We have already seen some of the built in directives.
The ngIf directive removes or recreates a portion of the DOM tree based on an {expression}
Creating Custom Directives
var app = angular.module('app', [])
app.directive('myDirective', [function(){
return {
link: function(scope, element, attrs) {
//Do something here.
}
}
}])
All you need to create your custom directive is to return a linking function that defines the behavior.
Linking function has access to:scope object, element, which is is the jqLite-wrapped element that this directive matches. and attributes: is a hash object with key-value pairs of normalized attribute names and their corresponding attribute values.
Basic behavior using element
app.directive('superwoman', [function(){
return {
restrict: "E",
link: function(scope, element, attrs) {
element.bind('mouseenter', function(){
alert("I'm busy saving the world. Come back later.")
})
}
}
}])
Example
Using attrs
app.directive('classy', [function(){
var link = function(scope, element, attrs) {
element.bind('mouseenter', function(){
element.addClass(attrs.classy);
})
}
return {
restrict:"A",
link: link
}
}])
Example
Using scope
app.controller('SuperController', ['$scope', function($scope){
$scope.totalSuperwomen = 20;
$scope.addOne = function() {
$scope.totalSuperwomen++;
}
}])
app.directive('superwoman', [function(){
return {
restrict: "E",
link: function(scope, element, attrs) {
element.bind('mouseenter', function(){
scope.addOne();
scope.$apply();
})
}
}
}])
Example
A Better Way
angular.module('App', [])
.directive('graph', function() {
return {
restrict: 'E',
scope: {
data: '=bindData', // bindings
width: '@width', // static value
color: '&color' // expression
},
link: Graph
};
function Graph(scope, element, attrs) { // Graph definition...
};
});
Example
Services
Reusable business logic independant of views.
// Simple GET request example :
$http.get('/someUrl').
success(function(data, status, headers, config) {
// this callback will be called asynchronously
// when the response is available
}).
error(function(data, status, headers, config) {
// called asynchronously if an error occurs
// or server returns response with an error status.
});
Angular services are:
Lazily instantiated – Angular only instantiates a service when an application component depends on it.
Services are Singletons – Each component dependent on a service gets a reference to the single instance generated by the service factory.
The $http service is a function which takes a single argument — a configuration object — that is used to generate an HTTP request and returns a promise with two $http specific methods: success and error.
app.controller("MainController", function($scope, userService){
$scope.users = userService.getUsers();
});
app.factory('userFactory', function($http){
var users = [];
$http.get('/someUrl').success(function(data){
users = data.users;
})
var getUsers = function(){
return users;
}
//...
return {
getUsers: getUsers,
//...
}
})
JSFiddle
Custom Filters
You can create your own to do anything.
angular.module('app')
.filter('numberFormat', [function () {
return function (number) {
if (number !== undefined) {
var abs = Math.abs(number);
if (abs >= Math.pow(10,12)) {//trillion
number = (number / Math.pow(10, 12)).toFixed(1)+ 't';
} else if (abs < Math.pow(10,12) && abs >= Math.pow(10, 9)) {//billion
number = (number / Math.pow(10, 9)).toFixed(1)+ 'b';
} else if (abs < Math.pow(10, 9) && abs >= Math.pow(10, 6)) {//million
number = (number / Math.pow(10, 6)).toFixed(1)+ 'm';
} else if (abs < Math.pow(10, 6) && abs >= Math.pow(10, 3)) {//thousand
number = (number / Math.pow(10,3)).toFixed(1)+ 'k';
}
}
return number;
};
}]);
Example
Routing
var app = angular.module('demoApp', [
'ngRoute'
]);
app.config(['$routeProvider',
function($routeProvider) {
$routeProvider.
when('/', {
templateUrl: 'partials/home.html',
controller: 'HomeController'
}).
when('/users/:userId', {
templateUrl: 'partials/user-detail.html',
controller: 'UserDetailController'
}).
otherwise({
redirectTo: '/'
});
}]);
Routes are used to map which path matches are linked to which controller. When you access a URL (by clicking on a link or putting in the URL), angular will first check to see if its defined and, if not, then it will delegate the event to a standard webpage view.
Other cools things that you can do is to define a url by using a variable in your scope. Here I have a users page. To define a specific user, I can create a new url for that user.
Debugging
Chrome developer tools for AngularJS
On your console:
//Gives you the last selected element on your html
var lastElement = angular.element($0);
//Gives you what is in your scope(functions, variables...)
lastElement.scope();
You have to include the css and angular-aria as well as material.
Once you do that you can start using material directives that comes with built in animations and functionalities.
watch for watchers.
Use one time binding.
Now you know
Creating your Angular modules.
Binding your data to your views.
Using services to organize and share code across your app.
Creating your own directives and using built in ones.
Using and creating filters.
Using routing.
This is more than I knew about when I created my first app. There is so much that you can build so fast with this information. I recommend you go and try building something simple that would implement these concepts before diving any deeper. You would be surprised how fast you get things done using Angular.
Angular 2 is a work in progress, many things can and will change.
Components
import {Component} from 'angular2/angular2';
@Component ({
selector: "user", // Defines the tag
injectables: [FavoritesService] //Gets the favorites data from FavoritesService class
})
The @Component annotation defines the HTML tag for the component by specifying the component's CSS selector.
View
import {Component, View, For, If} from 'angular2/angular2';
@Component ({
selector: "user"
})
@View ({
template:`
Hello {{name.value}}
`,
directives: [For, If]
})
The @View annotation defines the HTML that represents the component. The component you wrote uses an inline template, but you can also have an external template. To use an external template, specify a templateUrl property and give it the path to the HTML file.
You can also inject the other directives to the view here as the directives property.
Don't forget to import your directives on top of your documents.
Bootstraping
bootstrap(UserComponent);
On the bottom of your main app file call the bootsrap function and give the root component as an argument.
You only have to bootstrap the root component. Whenever Angular sees another component, it knows how to find it.
Bootstraping
All you need to add to your html to start your app is your component tag as well as your file scripts.
Angular applications are a tree of nested components. You always begin with a top-level component. You add child components by including them in the parent's template.
link to user
@RouteConfig({
path: '/user',
component: UserComponent
});
The router is responsible for mapping URLs to components.
What can you do today to prepare for Angular 2
You can start using ES6 today.
TypeScript is not nesessary for Anular 2 but I think it is cool. Most of you Java developers might have a better time with it than using plain JavaScript.
Most importantly write modular, good Angular 1.x code. This will allow make your transition more pleasant. You can start migrating your app slowly without breaking anything.
Angular2 Workshops and Resources
For more Angular 2 resources check here are some places to go.
Of course Angular's new website has the api referece and tutorials. Angular team with their new additions are doing a much better job this time with documenting and creating a new user friendly environment.
Angular U will be an amazing conference in June 22 to 25 2015 in San Francisco. All of the core team will be there and you can get a %20 discount.
Few new cool things
Custom (events) and [properties]
No more Scope.apply(knows about JS events)
Better error handling
Faster
No more curly braces for attribute values
Change detection will update on any other event you defined by using other libraries or plain JS. SetInterval will work fine.
Other Resources
AngularUI- has util functions, angular implementation of Bootstrap, Directives to integrate Google Maps and much more useful goodness.
The Angular Material - project is an implementation of Material Design in Angular.js
Egghead io has an amazing video series for getting your team up to speed with AngularJS.
ng-newsletter and AngularJS Magazine are both great for catching up with the latest and the greatest things about Angular.
This last one is a recent blog post that highlights few cool directives you can use.
Check out built with Angular website to get inspired and see who is using Angular in their projects.