Part 5: Module and Controller in Angular

In this article I'll discuss about Modules and Controllers in Angular Js.               

What is Module is Angular

An Angular Js modules defines an application. A module is a container for the different parts of an application.You can think of Module as a Main() function of programming language (like C,C++, C# or Java).

A module is created by using Angular Js function angular.module. We can create a module like

var myApp = angular.module("myModule", [])

The first parameter specifies the name of the Module and second parameter specifies the dependency for this Module . (we'll discuss modules later). In this we won't discuss about module dependency that's why I've passed an empty array as a second argument.


What is Controller in Angular

Angular Js applications are controlled by controllers. We can define a controller by using             ng-controller directive.In angular a controller is JavaScript function. 

How to create a Controller

Create a JavaScript function and assign it to Controller

var myController = function ($scope) {
    $scope.message = "Welcome to the World of Angular Js..!!";
}

What is $scope

$scope is a parameter that is passed to the controller function by angular framework. We attach the model to the $scope object, which will then be available in the view. With in the view, we can retrieve the data from the scope object and display.

Complete Example

Index.html file:

<!DOCTYPE html>
<html ng-app="MyApp">
<head>
    <script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.3.3/angular.min.js"></script>
    <script src="MyScript.js"></script>
    <title></title>
<meta charset="utf-8" />
</head>
<body ng-controller="myController">
    {{message}}
</body>

</html>

MyScript.js

var app = angular.module("MyApp", []);
app.controller("myController", function ($scope) {
    $scope.message = "Welcome to the World of Angular Js..!!"

});

(In the above example I've used an extrnal js file in which I've written all the angular code, and then I passed the reference of file in the Head Section.)

Output:


No comments:

Post a Comment