As previously mentioned, AngularJS directives are HTML attributes prefixed with “ng.”
The ng-init
directive is used to initialize variables in an AngularJS application.
<div ng-app=”” ng-init=”firstName=’John'”> <p>The name is <span ng-bind=”firstName”></span></p> </div> |
Alternatively, using valid HTML:
<div data-ng-app=”” data-ng-init=”firstName=’John'”> <p>The name is <span data-ng-bind=”firstName”></span></p> </div> |
If you want to ensure your page remains valid HTML, you can use data-ng- instead of ng-. |
AngularJS expressions are enclosed in double braces: {{ expression }}.
AngularJS will display the data precisely at the location where the expression is placed.
<!DOCTYPE html> <html> <script src=”https://ajax.googleapis.com/ajax/libs/angularjs/1.6.9/angular.min.js”></script> <body> <div ng-app=””> <p>My first expression: {{ 5 + 5 }}</p> </div> </body> </html> |
AngularJS expressions bind data to HTML in the same manner as the ng-bind directive.
<!DOCTYPE html> <html> <script src=”https://ajax.googleapis.com/ajax/libs/angularjs/1.6.9/angular.min.js”></script> <body> <div ng-app=””> <p>Name: <input type=”text” ng-model=”name”></p> <p>{{name}}</p> </div> </body> </html> |
AngularJS modules define AngularJS applications, while AngularJS controllers manage them.
The ng-app directive specifies the application, and the ng-controller directive designates the controller.
<div ng-app=”myApp“ ng-controller=”myCtrl“> First Name: <input type=”text” ng-model=”firstName”><br> Last Name: <input type=”text” ng-model=”lastName”><br> <br> Full Name: {{firstName + ” ” + lastName}} </div> <script> var app = angular.module(‘myApp‘, []); app.controller(‘myCtrl‘, function($scope) { $scope.firstName= “John”; $scope.lastName= “Doe”; }); </script> |
AngularJS modules are used to define applications.
var app = angular.module(‘myApp’, []); |
AngularJS controllers are responsible for managing applications.
app.controller(‘myCtrl’, function($scope) { $scope.firstName= “John”; $scope.lastName= “Doe”; }); |
You will explore modules and controllers in greater detail later in this tutorial.