Introduction to AngularJS

Created by Aysegul Yonet / @AysegulYonet

Slides:bit.ly/GDG-angular-slides

Why Angular?

  • AngularJS Features
  • Getting started
  • Views, Controllers and Scope
  • Directives, Filters
  • Services and Routes
  • What's new in Angular 2

ng-app




Hello {{name}}

JSFiddle

Modules


var myApp = angular.module("demoApp", ['ngMaterial']);
myApp.controller(...);
myApp.directive(...);
					

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;
	};	
})
					

Scope

Scope is the glue between application controller and the view.


JSFiddle

Directives

Angular Directives extends DOM behavior.

Creating Custom Directives


var app =  angular.module('app', [])
app.directive('myDirective', [function(){
	return {
		link: function(scope, element, attrs) {
			//Do something here.
		}
	}
}])
						


						

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.
});
					

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

Filters

Filters are used for formatting data displayed to the user.



  • {{country.name}}, {{country.code}}
Example

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: '/'
			});
	}]);
					

  • 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();
    					

    Angular Material

    
    
    
    
    					
    
    
    	
    
    					

    Performance

    
    
    • {{item}}

    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.

    Angular 2

    Components

    
    import {Component} from 'angular2/angular2';
    
    @Component ({
    	selector: "user", // Defines the  tag
    	injectables: [FavoritesService] //Gets the favorites data from  FavoritesService class
    })
    					

    View

    
    import {Component, View, For, If} from 'angular2/angular2';
    
    @Component ({
    	selector: "user"
    })
    
    @View ({
    	template:`
    		

    Hello {{name.value}}

    `, directives: [For, If] })

    Data Binding

    
    import {Component, View} from 'angular2/angular2';
    
    @Component ({
    	selector: "user",
    })
    
    @View ({
    	template:`
    		

    Hello {{name.value}}

    ` }) //Component controller export class UserComponent{ this.user = 'me'; }

    Bootstraping

    
    bootstrap(UserComponent);
    					

    Bootstraping

    
    
    	
    
    					

    Routers

    
    link to user
    @RouteConfig({
    	path: '/user', 
    	component: UserComponent
    });
    					

    What can you do today to prepare for Angular 2

    Angular2 Workshops and Resources

    Few new cool things

    • Custom (events) and [properties]
    • No more Scope.apply(knows about JS events)
    • Better error handling
    • Faster

    Other Resources

    THE END

    bit.ly/GDG-angular-slides
    @AysegulYonet