For creating controller and custom filters in Angular applications follow the below steps,
- Create a Student controller as StudentController.js. Add the following code to it to create a new module,
- var app = angular.module('app', []);
- Now create a controller in controller file and create AvgMarks function. Add the following code in Student controller,
- app.controller('studentController', function($scope)
- {
- $scope.helloAngular = 'I Learn';
- $scope.FirstName = 'Deepak';
- $scope.LastName = 'Upreti';
- $scope.studentdata = [
- {
- Name: 'Deepak Upreti',
- Id: 1,
- Sub1Marks: 80,
- Sub2Marks: 50,
- Sub3Marks: 40
- },
- {
- Name: 'Manu',
- Id: 2,
- Sub1Marks: 80,
- Sub2Marks: 70,
- Sub3Marks: 60
- }
- ];
- $scope.AvgMarks = function(sub1, sub2, sub3) {
- var total = sub1 + sub2 + sub3;
- return (total / 3);
- };
- });
- Now create a custom Filter as nameReverse for reversing the name. Also if you want you can create a separate JS file for the filter's logical separation. Add the following code,
- app.filter("nameReverse", function()
- {
- return function(name)
- {
- return name.split("").reverse().join("");
- };
- });
- Now insert the following code to your view, in this case, Index.cshtml file,
- <!DOCTYPE html>
- <html ng-app="app">
- <head>
- <title> Angular Page</title>
- </head>
- <body>
- <div ng-controller="studentController">
- {{helloAngular}}
- </div>
- <div ng-controller="studentController">
- Full Name: {{FirstName + " " + LastName}}
- </div>
- <br/><br/><br/>
- <div class="table-responsive">
- <table border="1" style="width:800px" ng-controller="studentController">
- <tr>
- <td><b>Name</b></td>
- <td><b>ReverseName</b></td>
- <td><b>Id</b></td>
- <td><b>Sub1Marks</b></td>
- <td><b>Sub2Marks</b></td>
- <td><b>Sub3Marks</b></td>
- <td><b>AverageMarks</b></td>
- </tr>
- <tr ng-repeat="s in studentdata">
- <td>{{s.Name}}</td>
- <td>{{s.Name | nameReverse}}</td>
- <td>{{s.Id}} </td>
- <td>{{s.Sub1Marks}} </td>
- <td>{{s.Sub2Marks}} </td>
- <td>{{s.Sub3Marks}} </td>
- <td>{{AvgMarks(s.Sub1Marks,s.Sub2Marks,s.Sub3Marks)}} </td>
- </tr>
- </table>
- </div>
- <script src="../../Scripts/angular.min.js"></script>
- <script src="../../Scripts/Controller/StudentController.js"></script>
- </body>
- </html>
- Run the application and you will get the following output,

- Now test the controller and new custom filter we created (“nameReverse”)


Join the conversation! Your thoughts help the community grow.