Create a new HTML file and paste the following content:
<!DOCTYPE html>
<html ng-app>
<head>
<title>Hello, Angular</title>
<script src="https://code.angularjs.org/1.5.8/angular.min.js"></script>
</head>
<body ng-init="name='World'">
<label>Name</label>
<input ng-model="name" />
<span>Hello, {{ name }}!</span>
<p ng-bind="name"></p>
</body>
</html>
When you open the file with a browser, you will see an input field followed by the text Hello, World!
. Editing the value in the input will update the text in real-time, without the need to refresh the whole page.
Explanation:
Load the Angular framework from a Content Delivery Network.
<script src="https://code.angularjs.org/1.5.8/angular.min.js"></script>
Define the HTML document as an Angular application with the ng-app
directive
<html ng-app>
Initialize the name
variable using ng-init
<body ng-init=" name = 'World' ">
Note that ng-init should be used for demonstrative and testing purposes only. When building an actual application, controllers should initialize the data.
Bind data from the model to the view on HTML controls. Bind an <input>
to the name
property with ng-model
<input ng-model="name" />
Display content from the model using double braces {{ }}
<span>Hello, {{ name }}</span>
Another way of binding the name
property is using ng-bind
instead of handlebars"{{ }}"
<span ng-bind="name"></span>
The last three steps establish the two way data-binding. Changes made to the input update the model, which is reflected in the view.
There is a difference between using handlebars and ng-bind
. If you use handlebars, you might see the actual Hello, {{name}}
as the page loads before the expression is resolved (before the data is loaded) whereas if you use ng-bind
, it will only show the data when the name is resolved. As an alternative the directive ng-cloak
can be used to prevent handlebars to display before it is compiled.