Module
A module in angularJs is a collection of services, directives, controllers, filters and configuration information. In simple words it is a container for different parts of an application.A module can be created in Angular as follows.
var app = angular.module("myApp", []);
angular.module() method takes two parameters.- First one is name of the module which is "myApp" in this example.
- Second one is dependencies for the module.( it will be discussed in future tutorials)
Controller
In Angular, controller is a JavaScript constructor function. It create a model (Data) for a view to display. Some times controller may make calls to server in order to obtain data for a view.
Example for a controller.
var myCtrl = function($scope) {
$scope.firstName = "John";
$scope.lastName = "Doe";
};
$scope is a angular object passed to this controller function by angular framework itself.
A model can be attached to this Scope object and it will be available in the view. Then the we can retrieve data in the view from Scope object using binding expressions.
Finally we have to register the controller with the module using controller() function.
app.controller("myCtrl", myCtrl);
controller() takes two parameters
- First parameter is the name of the controller ("myCtrl" in this example)
- Second parameter is the controller function.
A Complete example of using Controllers and Models
<!DOCTYPE html>
<html>
<script src="scripts/angular.min.js"></script>
<body>
<div ng-app="myApp" ng-controller="myCtrl">
{{ firstName + " " + lastName }}
</div>
<script>
var app = angular.module("myApp", []);
var myCtrl = function($scope) {
$scope.firstName = "John";
$scope.lastName = "Doe";
};
app.controller("myCtrl", myCtrl);
</script>
</body>
</html>
creating and adding it to module can be done in the same Line.
app.controller("myCtrl", function($scope) {
$scope.firstName = "John";
$scope.lastName = "Doe";
}
);
please add a comment if anything is not clear or you have something to add.
Angular 2 is an open source JavaScript framework to build web applications in HTML and JavaScript and has been conceived as a mobile first approach.
ReplyDeleteYou should have a basic understanding of JavaScript and any text editor. As we are going to develop web-based applications using Angular 2, it will be good if you have an understanding of other web technologies such as HTML, CSS, AJAX, AngularJS etc.
Read more: AngularJS Training and Tutorial