AngularJS – HTML enhanced for web apps!



AngularJS – HTML enhanced for web apps!

0 0


ac-angular1.x


On Github AnnieCannons / ac-angular1.x

AngularJS

Aysegul Yonet / @AysegulYonet

Slides: bit.ly/angular-slides

What we will build?

Catstagram

What we will learn today?

  • What is AngularJS and why you might want to use it.
  • Parts that makes an Angular application:
    • Controllers
    • Directives
    • Services
  • Debugging your angular app.
  • Animation
  • Routing
  • Resources and open source directives
We will look at some built-in directives and filters, then we'll create our own.

What we will start with?

Fork the repo Yonet/Catstagram Download Files Here

What is Angular?

If you were to build facebook from skretch, how would you build it? What needs to be different than a static website?

AngularJS lets you extend HTML vocabulary for your application.

Example

Angular Modules

Binding

You can bootstrap your angular app by adding ng-app to any html tag.

example

Only one AngularJS application can be auto-bootstrapped per HTML document. The first ngApp found in the document will be used to define the root element to auto-bootstrap as an application. To run multiple applications in an HTML document you must manually bootstrap them using angular.bootstrap instead. AngularJS applications cannot be nested within each other.

Modules

You can think of a module as a container for the different parts of your app – controllers, services, filters, directives, ...

var app = angular.module('myApp', []);
Modules makes your code, more readable, maintainable and testable.

Scopes

Scope is the glue between application controller and the view. Everything you need to be available in your html, you have to include it in your $scope object.

example

Scopes are arranged in hierarchical structure which mimic the DOM structure of the application. Scopes provide APIs ($watch) to observe model mutations. ($apply) to propagate any model changes through the system into the view from outside of the "Angular realm" (controllers, services, Angular event handlers).

Controllers

  • Set up the initial state of the $scope object.
  • Add behavior to the $scope object.
var app = angular.module('myApp', []);
app.controller("FirstController", ['$scope', function($scope) {
	$scope.message = 'Hello World!';
	//Cool functions goes here...
}]);

example

It is important that the name starts with a capital letter, camel case and Ends with Controller. Controllers are view agnostic. Both controllers and directives have reference to the scope, but not to each other.

Exercise

Filters

Filters are used for formatting data displayed to the user.

example

Built-in Filters

List of built-in filters

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

Exercise time...

Solutions

Directives

Directives let you invent new HTML syntax, specific to your application.

Built-in Directives

Angular comes with great directives you can use.

List of built-in directives

Exercise

Solution

angular.element

If jQuery is available, angular.element is an alias for the jQuery function. If jQuery is not available, angular.element delegates to Angular's built-in subset of jQuery, called "jQuery lite" or "jqLite."

Angular's jqLite

What I am trying to say is you use angular.element no matter what.

Mouse Events with Angular

ngShow/ngHide

ngSwitch/ngIf

Example

Exercise 1

Exercise 2

Solution 1

Solution 2

Creating Custom Directives

A linking function is enough to create a directive.

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

Linking function has access to:

  • scope: is an Angular scope object.
  • element: is the jqLite-wrapped element that this directive matches.
  • attrs: is a hash object with key-value pairs of normalized attribute names and their corresponding attribute values.

var app =  angular.module('app', [])
app.directive('myDirective', [function(){
	return {
		restrict: "E", //Defaults to "A" for attribute. 
		link: function(scope, element, attrs) {
			//Do something here...
		}
	}
}])
Example

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

Services

The service factory function generates the single object or function that represents the service to the rest of the application.

You can use services to organize and share code across your app.

Built-in Services

  • $http
  • $filter
  • $rootScope
  • $location service parses the URL in the browser address bar and makes the URL available to your application.
  • $animate is available in the AngularJS core, however, the ngAnimate module must be included to enable full out animation support. Otherwise, $animate will only perform simple DOM manipulation operations.
Like other core Angular identifiers, built-in services always start with $ (e.g. $http).

$http

// 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.
});
// Simple POST request example (passing data) :
$http.post('/someUrl', {msg:'hello word!'}).
  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.
  });
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.

Custom Services

The service factory function generates the single object or function that represents the service to the rest of the application.

Example Services are often used for getter and setter functions.

Exercise time...

Solutions

Injecting Dependencies

Dependency Injection is a software design pattern that deals with how components get hold of their dependencies.

var app = angular.module('myApp', [
  'ui.router',
  'myControllers'
]);

app.controller('MainController', ['$scope', '$http', function($scope, $http){
	//
}])
VERY IMPORTANT, order of dependencies matter. $scope is always first.

Angular UI

The companion suite(s) to the AngularJS framework.

var app = angular.module('myApp', [
  'ngRoute',
  'myControllers', 
  'ui.map'
]);

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

Animations

AngularJS 1.3 provides animation hooks for common directives such as ngRepeat, ngSwitch, and ngView, as well as custom directives via the $animate service.

example

Yeo


					

More Resources

THE END

BY Aysegul Yonet / aysegulyonet@gmail.com

AngularJS Aysegul Yonet / @AysegulYonet Slides: bit.ly/angular-slides