By Daniel Lo Nigro, with portions from Glen Maddern with permission. Licensed under a Creative Commons Attribution-ShareAlike 3.0 Unported License.
{{
and }}
<!DOCTYPE html> <html ng-app> <body> <h1>1 + 2 = {{ 1 + 2 }}</h1> <script src="angular.js"></script> </body> </html>
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}}!
$scope
$rootScope
<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}}
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>
$
(eg. $http
)
var services = angular.module('myApp.services', []); services.factory('helloWorldService', function() { ... });
var BlahController = function($scope, $http, helloWorldService) {
Let you extend HTML with your own stuff. Teach HTML new tricks.
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}}
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" />