AngularJS Controller As Syntax

Overview

In this article, we will see AngularJS Controller as syntax. Thus, we used $scope mechanism to make members of the controllers, available in their respective views. We will see the details in this article. Thus, let's start-

For more articles on AngularJS, kindly refer-

Introduction

Lets create an empty Application. Add a simple HTML file. Now, add a JavaScript file, name it as script.js.

In this script file, drag drop the reference of angularmin.js file reference, as given below-
  1. /// <reference path="angular.min.js" />  
Now, add a module name and controller name. In this controller, attach a $scope object and in this, display a Hello Message, as given below-
  1. var app = angular.module("Demo", []);  
  2. app.controller("mainController"function ($scope) {  
  3. $scope.message = "Hello C-sharpcorner";  
  4.   
  5. });  
Now, go back to our HTML Page, which we had created earlier, add the reference of Angular script file and our script file.
  1. <script src="scripts/angular.min.js"></script>  
  2.   
  3. <script src="scripts/script.js"></script>  
Now, add ng-controller name and ng-app name in HTML tag and just bind the message property.
  1. <html ng-app="Demo">  
Our module name is Demo and Controller name is mainController, which is given below-
  1. <h1 ng-controller="mainController">  
Now, let's bind the message property here-
  1. <h1 ng-controller="mainController">  
  2.   
  3.       {{message}}  
  4.   </h1>  
Now, let's save the changes and lets reload the page. We will see the output, given below-

output

We got Hello Csharpcorner output now. When you see the controller, we are injecting $scope object to members of the controllers, available to their respective views, which we don’t need, so we can get rid of $scope object here and use-
  1. var app = angular.module("Demo", []);  
  2.   
  3. app.controller("mainController"function () {  
  4.     this.message = "Hello C-sharpcorner";  
  5.   
  6. });  
In our HTML page, we are using ng-controller directive and we are specifying the controller name too. We will use a keyword and alias , which you want to use.

Now, you will pass that alias, which you had used in your binding expression property, as given below-
  1. <h1 ng-controller="mainController as mainCtrl">  
  2.   
  3.       {{mainCtrl.message}}  
  4.   </h1>  
Save the changes and reload the page, given below-

output

You can see, we got the same output without using $scope object here . Let's see, how to use Controller as syntax. To see that, we will use the same example DemoApplication, which we used in our previous Applications also.

In this example, the script file contains the code, given below-
  1. /// <reference path="angular.min.js" />  
  2. /// <reference path="angular-route.min.js" />  
  3.   
  4.   
  5.   
  6. var app = angular.module("Demo", ["ngRoute"])  
  7.                     .config(function ($routeProvider, $locationProvider) {  
  8.                         $routeProvider  
  9.   
  10.                         .when("/home", {  
  11.                             templateUrl: "Templates/home.html",  
  12.                             controller: "homeController"  
  13.                         })  
  14.   
  15.   
  16.                           .when("/courses", {  
  17.                               templateUrl: "Templates/courses.html",  
  18.                               controller: "coursesController"  
  19.                           })  
  20.   
  21.                            .when("/students", {  
  22.                                templateUrl: "Templates/students.html",  
  23.                                controller: "studentsController"  
  24.                            })  
  25.   
  26.                                 .when("/students/:id", {  
  27.                                     templateUrl: "Templates/StudentDetail.html",  
  28.                                     controller: "StudentDetailController"  
  29.                                 })  
  30.                         .otherwise({  
  31.                             redirectTo: "/home"  
  32.                         })  
  33.                         $locationProvider.html5Mode(true);  
  34.                     })  
  35.   
  36.                 .controller("homeController"function ($scope) {  
  37.                     $scope.message = "Home Page";  
  38.                 })  
  39.   
  40.                  .controller("coursesController"function ($scope) {  
  41.                      $scope.courses = ["c#""SQL""Oracle"];  
  42.                  })  
  43.   
  44.                 .controller("studentsController"function ($scope, $http) {  
  45.                     $http.get("StudentService.asmx/GetAllStudents")  
  46.                     .then(function (response) {  
  47.   
  48.                         $scope.students = response.data;  
  49.   
  50.                     })  
  51.   
  52.   
  53.                 })  
  54.   
  55.   .controller("StudentDetailController"function ($scope, $http, $routeParams) {  
  56.       $http({  
  57.           url: "StudentService.asmx/GetStudents",  
  58.           params: { id: $routeParams.id },  
  59.           method:"get"  
  60.       })  
  61.       .then(function (response) {  
  62.   
  63.           $scope.student = response.data;  
  64.   
  65.       })  
  66.   
  67.   });  
Now, we are going to rename the Controller name, as given below-
  1. controller: "homeController as homeCtrl"  
  2.   
  3. controller: "coursesController as coursesCtrl"  
  4.   
  5. controller: "studentsController as studentsCtrl"  
  6.   
  7. controller: "StudentDetailController as StudentDetailCtrl"  
Thus, this was our first change. Now, the next change is to get rid of $scope object and use this, as given below-
  1. .controller("homeController"function () {  
  2.                   this.message = "Home Page";  
  3.               })  
  4.   
  5.                .controller("coursesController"function () {  
  6.                    this.courses = ["c#""SQL""Oracle"];  
  7.                })  
Now, notice, we have StudentsController and StudentsDetailsController, as we can get rid of $scope object from the parameter but we can get rid of where we had used  it in our response, as we are using http GET request. We will remove and replace with this. See how it behaves. Thus, for our StudentsController and StudentsDetailsController code is given below-
  1. .controller("studentsController"function ( $http) {  
  2.                   $http.get("StudentService.asmx/GetAllStudents")  
  3.                   .then(function (response) {  
  4.   
  5.                       $scope.students = response.data;  
  6.   
  7.                   })  
  8.   
  9.   
  10.               })  
  11.   
  12. .controller("StudentDetailController"function ( $http, $routeParams) {  
  13.     $http({  
  14.         url: "StudentService.asmx/GetStudents",  
  15.         params: { id: $routeParams.id },  
  16.         method:"get"  
  17.     })  
  18.     .then(function (response) {  
  19.   
  20.         this.student = response.data;  
  21.   
  22.     })  
We need to make the changes in our respective views also. Let's go back to our courses.html view and now we had used coursesCtrl as an alias. We will put in the ng-repeat directive, which we had lopped through those records, as given below-
  1. <li ng-repeat="course in coursesCtrl.courses">  
  2.          {{course}}  
  3.   
  4.      </li>  
Make changes in Home View also, as given below-
  1. <h1>{{homeCtrl.message}}</h1>  
Similarly, lets do it for the students details, as given below-
  1. <table style="border:1px solid black">  
  2.     <tr>  
  3.         <td>Id</td>  
  4.         <td>{{StudentDetailCtrl.student.id}}</td>  
  5.     </tr>  
  6.     <tr>  
  7.         <td>Name</td>  
  8.         <td>{{StudentDetailCtrl.student.name}}</td>  
  9.     </tr>  
  10.     <tr>  
  11.         <td>City</td>  
  12.         <td>{{StudentDetailCtrl.student.city}}</td>  
  13.   
  14.     </tr>  
  15.     <tr>  
  16.         <td>Gender</td>  
  17.         <td>{{StudentDetailCtrl.student.gender}}</td>  
  18.     </tr>  
  19. </table>  
  20. <a href="students">Back To List </a>  
Similarly, do it for students, as given below-
  1. <li ng-repeat="student in studentsCtrl.students">  
  2.       <a href="students/{{student.id}}">  
  3.           {{student.name}}  
  4.       </a>  
  5.   </li>  
Save the changes and run the Application.

application

Click Courses. You will see the output but when we click students, we found no data has populated.

application

When you click on developer tools options, you will see the error also.

error

This is because we had used this keyword in reposnse data in StudentsController and StudentsDetailsController.

StudentsDetailsController

Now, here this.students = response.data is actually pointing to the Window object and not to the instance of the their respective controllers. Due to this, we are not able to load the data from Webservice. To make it work, we will create a variable.
  1. var vm = this;  
Now, attach this variable to students, as given below-

 

  1. vm.students = response.data;  
Similarly, for students details controller, use the code given below-
  1. var vm = this;  
  2. vm.student = response.data;  
Thus, our final script.js code is given below-
  1. /// <reference path="angular.min.js" />  
  2. /// <reference path="angular-route.min.js" />  
  3.   
  4.   
  5.   
  6. var app = angular.module("Demo", ["ngRoute"])  
  7.                     .config(function ($routeProvider, $locationProvider) {  
  8.                         $routeProvider  
  9.   
  10.                         .when("/home", {  
  11.                             templateUrl: "Templates/home.html",  
  12.                             controller: "homeController as homeCtrl"  
  13.                         })  
  14.   
  15.   
  16.                           .when("/courses", {  
  17.                               templateUrl: "Templates/courses.html",  
  18.                               controller: "coursesController as coursesCtrl"  
  19.                           })  
  20.   
  21.                            .when("/students", {  
  22.                                templateUrl: "Templates/students.html",  
  23.                                controller: "studentsController as studentsCtrl"  
  24.                            })  
  25.   
  26.                                 .when("/students/:id", {  
  27.                                     templateUrl: "Templates/StudentDetail.html",  
  28.                                     controller: "StudentDetailController as StudentDetailCtrl"  
  29.                                 })  
  30.                         .otherwise({  
  31.                             redirectTo: "/home"  
  32.                         })  
  33.                         $locationProvider.html5Mode(true);  
  34.                     })  
  35.   
  36.                 .controller("homeController"function () {  
  37.                     this.message = "Home Page";  
  38.                 })  
  39.   
  40.                  .controller("coursesController"function () {  
  41.                      this.courses = ["c#""SQL""Oracle"];  
  42.                  })  
  43.   
  44.                 .controller("studentsController"function ($http) {  
  45.                     var vm = this;  
  46.                     $http.get("StudentService.asmx/GetAllStudents")  
  47.                     .then(function (response) {  
  48.                         vm.students = response.data;  
  49.                     })  
  50.                       })  
  51.       .controller("StudentDetailController"function ( $http, $routeParams) {  
  52.           var vm = this;  
  53.           $http({  
  54.           url: "StudentService.asmx/GetStudents",  
  55.           params: { id: $routeParams.id },  
  56.           method:"get"  
  57.       })  
  58.       .then(function (response) {  
  59.           vm.student = response.data;  
  60.       })  
  61.   });  
Now, let's save the changes and reload the page, as given below-

Page

As you can see from the output, we got the list of the students from our database, which means our Webservice is working fine. When you click the detail of it, the particular ID also displays the property.

Page

Thus, we got the output.

Conclusion

This was about AngularJS Controller as syntax. Hope this article was helpful!!


Similar Articles