AngularJS Application
Now is the time to create a real AngularJS single page web application (SPA).
AngularJS Application Example
You have learned enough about AngularJS, and now you can start creating your first AngularJS application:
My Notes
Remaining characters:100
Application Explanation
AngularJS Examples
<head>
<meta charset="utf-8">
<script src="https://cdn.staticfile.net/angular.js/1.4.6/angular.min.js"></script>
</head>
<body>
<div ng-controller="myNoteCtrl">
<h2>My Notes</h2>
<p><textarea ng-model="message" cols="40" rows="10"></textarea></p>
<p>
<button ng-click="save()">Save</button>
<button ng-click="clear()">Clear</button>
</p>
<p>Number of characters left: <span ng-bind="left()"></span></p>
</div>
<script src="myNoteApp.js"></script>
<script src="myNoteCtrl.js"></script>
</body>
</html>
Try it Yourself »
The application file "myNoteApp.js":
The controller file "myNoteCtrl.js":
$scope.message = "";
$scope.left = function() {return 100 - $scope.message.length;};
$scope.clear = function() {$scope.message = "";};
$scope.save = function() {alert("Note Saved");};
});
<html> element is the AngularJS application: ng-app="myNoteApp" 's container:
The <div> element is the controller in the HTML page: ng-controller="myNoteCtrl" 's scope:
ng-modelThe directive binds the <textarea> to the controller variable message:
Twong-clickEvents invoke controller functionsclear()andsave():
<button ng-click="clear()">Clear</button>
ng-bindDirectives bind controller functionsleft()to <span>, used to display the remaining characters:
The application library file needs to be executed after AngularJS is loaded:
<script src="myNoteCtrl.js"></script>
AngularJS application architecture
The above example is a complete AngularJS single page web application (SPA).
The <html> element contains the AngularJS application (ng-app=)。
The <div> element defines the scope of the AngularJS controller (ng-controller=)。
An application can have many controllers.
Application file(my...App.js) defines the application model code.
One or more controller files (my...Ctrl.js) defines the controller code.
Summary - How does it work?
The ng-app directive is placed at the root element of the application.
For a single page web application (SPA), the root of the application is typically the <html> element.
One or more ng-controller directives define the controllers of the application. Each controller has its own scope: : the defined HTML element.
AngularJS starts automatically on the HTML DOMContentLoaded event. If the ng-app directive is found, AngularJS loads the module specified in the directive and compiles the application with ng-app as its root.
The root of an application can be the entire page, or a small part of the page; if it is a small part, it will compile and execute faster.
other extensions