AngularJS ng-app and ng-init

Learn how ng-app bootstraps an AngularJS application and how ng-init sets up initial scope data for quick examples.

The ng-app Directive

ng-app marks the HTML element where an AngularJS application begins. When AngularJS loads, it looks for this attribute, and everything inside that element becomes part of the application — able to use directives, expressions, and data binding.

Example

<!DOCTYPE html>
<html>
<head>
  <script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.8.2/angular.min.js"></script>
</head>
<body>

<div ng-app="">
  <p>The value is {{ 42 }}</p>
</div>

</body>
</html>

ng-app can also be given a name, such as ng-app="myApp", which links the HTML to a module you define in JavaScript with angular.module("myApp", []). An empty ng-app="" is fine for small standalone examples that do not need a named module.

The ng-init Directive

ng-init lets you set an initial value on the scope directly from HTML, before any expression uses it. It is mainly useful for demonstrations, quick prototypes, and initializing loop data for ng-repeat.

Example

<!DOCTYPE html>
<html>
<head>
  <script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.8.2/angular.min.js"></script>
</head>
<body>

<div ng-app="" ng-init="quantity=5;price=20">
  <p>Total: {{ quantity * price }}</p>
</div>

</body>
</html>

Example

<!DOCTYPE html>
<html>
<head>
  <script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.8.2/angular.min.js"></script>
</head>
<body>

<div ng-app="" ng-init="fruits=['Apple','Banana','Cherry']">
  <p>First fruit: {{ fruits[0] }}</p>
  <p>Fruit count: {{ fruits.length }}</p>
</div>

</body>
</html>
Note: ng-init is convenient for small examples, but real applications should initialize data inside a controller function instead. Putting application logic directly in HTML attributes makes it harder to test and to reuse.
DirectivePurpose
ng-appMarks the root element of an AngularJS application and bootstraps it
ng-initSets initial values on the scope for that element and its children
  • Use ng-app to define where AngularJS should take control of the page
  • Use ng-init only for simple demo values or to seed data for ng-repeat
  • Prefer a controller and $scope for anything beyond trivial initialization
Note: You can nest ng-init data structures — objects, arrays, even arrays of objects — which makes it handy for quickly demoing ng-repeat without writing a controller.