Getting Started
Setup & Bootstrap
AngularJS (1.x) is included via a script tag. ng-app bootstraps the application and ng-controller wires a controller to a DOM subtree. Double curly braces {{ }} are Angular expressions that render model data.
<!-- include AngularJS 1.8.x -->
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.8.2/angular.min.js"></script>
<body ng-app="myApp">
<div ng-controller="MainCtrl">
{{ message }}
</div>
</body>
<script>
var app = angular.module('myApp', []);
app.controller('MainCtrl', function($scope) {
$scope.message = 'Hello AngularJS!';
});
</script>ng-app & Auto-Bootstrap
ng-app with a module name auto-bootstraps AngularJS on DOMContentLoaded. ng-strict-di forces explicit dependency annotations, catching minification bugs early in development. Only one ng-app is auto-bootstrapped per page.
<!-- ng-app on <html> makes the whole page an Angular app -->
<html ng-app="myApp" ng-strict-di>
<head><title>App</title></head>
<body>
<div>{{ 1 + 2 }}</div>
</body>
</html>
<!-- ng-strict-di enforces dependency injection annotations -->
<!-- (errors if a service uses implicit DI without annotation) -->Manual Bootstrap
Use angular.bootstrap() when you need to delay startup (e.g., waiting for async module loading or a fetched config). You can bootstrap multiple Angular apps on one page this way, each on its own root element.
<!-- HTML has NO ng-app attribute -->
<div id="appRoot">
{{ message }}
</div>
<script>
angular.element(document).ready(function() {
angular.bootstrap(document.getElementById('appRoot'), ['myApp']);
});
</script>First Data Binding
With ng-app and no module name, Angular runs in 'auto' mode with the default ng module. ng-model binds the input to a property named 'name' on the implicit scope, and {{ }} renders it live. This is two-way data binding in its simplest form.
<div ng-app>
<label>Your name:
<input type="text" ng-model="name">
</label>
<p>Hello {{ name || 'stranger' }}!</p>
</div>Module & Controller Basics
angular.module('name', [deps]) creates a module; angular.module('name') retrieves an existing one. The inline array annotation ['$scope', function($scope){}] keeps the controller minification-safe. Always pass dependencies explicitly to the module when creating it.
var app = angular.module('myApp', []); // create module
// ^name ^dependencies
app.controller('GreetCtrl', ['$scope', function($scope) {
$scope.user = { name: 'Ada' };
$scope.greet = function() {
return 'Hi ' + $scope.user.name;
};
}]);Modules
Creating vs Retrieving a Module
The two-argument form angular.module(name, deps) creates a new module. The one-argument form angular.module(name) retrieves a previously defined one. Accidentally passing [] twice silently wipes the module's registrations.