This is Our Blog

Working with Modules, Controllers and Directives in AngularJS

What is Controller in AngularJS
A controller is a JavaScript object containing attributes/properties and functions. Each controller accepts $scope as a parameter which refers to the application/module that controller is to control.
What is Module in AngularJS?
A module is a collection of services, directives, controllers, filters, and configuration information. angular.module is used to configure.

var app = angular.module("myapp", []);
    app.controller("EmployeeController", function () {
        this.Code=44;
this.Name=”Demo Employee”;
this.SaveEmployee=function()
{
//Logic to save Employee record
};
});

Here in above example we have used angular.module to define a module and the parameters to this methods are the name of the controller that you want to add to the angular module and the second parameter is the list of dependencies for current controller to work. Initially in the above example we do not have any dependencies so we have left the [ ] Blank.
In the above example we have created a module with name “myapp” and added a controller to this module and the name of the controller is “EmployeeController”.
In the above defined controller we have defined two properties and a function which will be associated with this “EmployeeController”.

What is Directive?
Directives are a way to teach HTML new tricks. During DOM compilation directives are matched against the HTML and executed. This allows directives to register behavior, or transform the DOM.
An example of using some of the directives is given bellow:-

Using controller and modules on HTML page

<input type="text" />
<h1>{{message}}</h1>
<table>
<tbody>
<tr>
<td>{{i.Name}}</td>
<td>{{i.Address}}</td>
</tr>
</tbody>
</table>
<form id="addEmployeeForm">
<input id="Name" name="Name" required="" type="text" />
<input id="Address" name="Address" required="" type="text" />
<select id="Dep_Id" name="Dep_Id">
<option>Select an Department</option>
<option value="{{t.Id}}" data-ng-repeat="t in Departments">{{t.Name}}</option>
</select>
<table>
<tbody>
<tr>
<td>Name</td>
</tr>
<tr>
<td>Address</td>
<td>Department</td>
<th><input type="submit" value="Save Data!" /></th>
</tr>
</tbody>
</table>
</form>

In the above example we are using ng-app directive to tell angular the scope for code execution and anything outside this will not be able to use angular for instance if you have used ng-app directive with a div so inside that div anything that angular can recognized will work but if anything outside that div is written which may use angular expressions or directives will not work. There can be only one ng-app on page.
In the above example we are refereeing to module with name “myapp” in the ng-app and also if you notice we have used ng-controller to specify which controller we would like to use in the given scope. In above we wanted to use the code written in the “EmployeeController”.
In the above code we have also used ng-moodel for binding. We can use ng-model to bind our control to the model property. In out model for Employee we have used Name and address that we are displaying in table.
Also as you can see we have used ng-repeat directive which acts very much same as $each(in jquery)/ foreach in c#. where are iterating through “Employees” which contains the list of employee objects.

The Scripting code is given bellow:-

First script file

var EmployeeController = function ($scope, empService) {
    $scope.message = "Hello From Angular";
    $scope.isShow = true;
    empService.getDepartment().then(function (data) {
        $scope.Departments = data;
    });
    empService.getEmployee().then(function (data) {
        $scope.Employees = data;
    });
    $scope.submit = function () {
        empService.addEmployee("/api/EmployeeOperations/AddEmployee",
            "POST", $scope.formData).then(function (data) {
                $scope.Employees = data;
                $scope.formData = "";
            });
    }
};
var MyApp = angular.module("myapp", []);
MyApp.controller("EmployeeController", EmployeeController);

In the first script file as you can see we are creating an object with name “EmployeeController” which actually contains the reference of properties and functions that we would like to use in our controller. In the anonymous function used for initializing controller object we have used two parameters. First is one that we will use for making http requests to our service which will actually get the data and save the data if required and second is the name of custom service object which will have method for various operations and you can see the implementation of this in the script code given bellow.

Second Script File:-

(function () {
    var empService = function ($http) {
        var getEmp = function () {
            return $http.get("/api/EmployeeOperations/GetAllEmployees").then(function (response) {
                return response.data;
            });
        };
        var getDep = function () {
            return $http.get("/api/EmployeeOperations/GetAllDepartments").then(function (response) {
                return response.data;
            });
        };
        var addEmployee = function (address, methodType, values) {
            return $http({
                url: address,
                method: methodType,
                data: values
            }
             ).then(function () {
                 return getEmp();
             });
        }
        return {
            getEmployee: getEmp,
            getDepartment: getDep,
            addEmployee: addEmployee
        };
    };

    var module = angular.module("myapp");
    module.factory("empService", empService);
})();

In the second script code we have written some service code to make http requests to our rest service.
getEmp is used to make http get request to the service and what data we get from here we use it to display data on page. We are using “$http.get” function for this.

addEmployee is used to adding a new employee to the database through. This function takes some parameters
1 service url
2 Method(Get,Post etc)
3. Data

getDep to get the list of departments.

And all these function are combined in a Javascript object which is returned be the following statement.
return {
getEmployee: getEmp,
getDepartment: getDep,
addEmployee: addEmployee
};

So the subscriber call will use getEmployee, getDepartment and addEmployee to access the functionality where ever this service is referenced.

<form id="addEmployeeForm">
<input id="Name" name="Name" required="" type="text" />
<input id="Address" name="Address" required="" type="text" />
<select id="Dep_Id" name="Dep_Id">
<option>Select an Department</option>
<option value="{{t.Id}}" data-ng-repeat="t in Departments">{{t.Name}}</option>
</select>
<table>
<tbody>
<tr>
<td>Name</td>
</tr>
<tr>
<td>Address</td>
<td>Department</td>
<th><input type="submit" value="Save Data!" /></th>
</tr>
</tbody>
</table>

In the above code I was required to save the employee data to the database. So for this we used ng-model directive and stored all the data in “formData” . As you can see we have used form.Data.Name, form.Data.Address and form.Data.Dep_Id which actually are model properties that we are required to pass to service in order to save data.
In Employee Controller we have defined Sumit function which actually calls service method to save data.
Also would like to tell you we have used here a special detective ng-submit which is used for specifying which action should take place when form is submitted.



0 Comments


Would you like to share your thoughts?

Would you like to share your thoughts?

Leave a Reply

This site uses Akismet to reduce spam. Learn how your comment data is processed.