AngularJS

HTML enhanced for modern web apps

By Daniel Lo Nigro, with portions from Glen Maddern with permission. Licensed under a Creative Commons Attribution-ShareAlike 3.0 Unported License.

"Regular" HTML+JS

AngularJS

AngularJS

Components

Basic Angular

<!DOCTYPE html>
<html ng-app>
<body>
	<h1>1 + 2 = {{ 1 + 2 }}</h1>
	<script src="angular.js"></script>
</body>
</html>
			

1 + 2 = {{ 1 + 2 }}

Two-way binding

Still no JavaScript required!

<!DOCTYPE html>
<html ng-app>
<body>
	<label for="name">What is your name?</label>
	<input id="name" ng-model="name" />
	<p>Hi there, {{name}}!</p>
	<script src="angular.js"></script>
</body>
</html>
			

Hi there, {{name}}!

Controllers

$scope

Controllers

<body ng-controller="HelloController">
	<input ng-model="name" size="20" />
	<p>Hi there, {{name}}</p>
	<button ng-click="resetName()">Reset</button>

	<script>
	var HelloController = function($scope) {
		$scope.resetName = function() {
			$scope.name = "Daniel L"; 
		};
		$scope.resetName(); // Set initial state
	};
	</script>
	<script src="angular.js"></script>
</body>
			

Hi there, {{name}}

ng-repeat

One of the most useful directives in AngularJS

<body ng-controller="BlogController">
	<ul>
		<li ng-repeat="post in posts">
			{{post.title}} at {{post.date | date}}
		</li>
	</ul>
	<button ng-click="addNewPost()">Add another</button>
	<script>
	var BlogController = function($scope) {
		$scope.posts = [
			{ title: 'First Post', date: new Date(2012, 11, 12) },
			{ title: 'Second Post', date: new Date(2013, 0, 10) }
		];
		$scope.addNewPost = function() {
			$scope.posts.push({ title: 'Test ' + $scope.posts.length, date: new Date() });
		};
	};
	</script>
</body>
  • {{post.title}} at {{post.date | date}}

Services and DI

Custom Directives

Let you extend HTML with your own stuff. Teach HTML new tricks.

Click to Edit

Without directives

<div ng-hide="editorEnabled">
	<p ng-click="editorEnabled = true">
		{{title}}
	</p>
</div>

<div ng-show="editorEnabled">
	<form ng-submit="editorEnabled = false">
		<input type="text" ng-model="title" />
		<input type="submit" value="Save" />
	</form>
</div>
			

{{title}}

Click to Edit

With directives

var module = angular
	.module('myApp', [])
	.directive('clickToEdit', function () {
		return {
			restrict: 'E', // This directive applies to Elements
			scope: {
				text: '@'    // Pass text attribute into scope
			},
			link: function (scope, element, attrs) {
				scope.editorEnabled = false;
			},
			template: 
'<div ng-hide="editorEnabled"><p ng-click="editorEnabled = true">{{text}}</p></div>'+
'<div ng-show="editorEnabled">'+
'<form ng-submit="editorEnabled = false">'+
	'<input type="text" ng-model="text" size="100">'+
	'<input type="submit" value="Save">'+
'</form>'+
'</div>'
		}
	});
			
<click-to-edit text="Hello World" />

And more...

Demo