In day 21 of AngularJS article series, we are going to learn the next key players/concept of AngularJS, and understand the concept of Controller as syntax of AngularJS. Before moving to the key players/concepts of AngularJS, please read my previous articles:
- Introduction to AngularJS – Day 1
- Introduction to AngularJS – Day 2
- Introduction to AngularJS – Day 3
- Introduction to AngularJS – Day 4
- Introduction to AngularJS – Day 5
- Introduction to AngularJS – Day 6
- Introduction to AngularJS – Day 7
- Introduction to AngularJS – Day 8
- Introduction to AngularJS – Day 9
- Introduction to AngularJS – Day 10
- Introduction to AngularJS – Day 11
- Introduction to AngularJS – Day 12
- Introduction to AngularJS – Day 13
- Introduction To AngularJS – Day 14
- Introduction To AngularJS – Day 15
- Introduction To AngularJS – Day 16
- Introduction to AngularJS – Day 17
- Introduction to AngularJS – Day 18
- Introduction to AngularJS – Day 19
- Introduction To AngularJS - Day 20
Controller as
AngularJS version 1.2 added a new feature that is nothing but ‘controller as’ syntax. It defines ‘named scope’. You can use this with the help of ng-controller directive. It defines properties on the functions (Controller), not the ‘$scope’.
Example - I created a controller name ‘AuthorCtrl as author’, here ‘author’ is nothing but my ‘named scope’.
The following example shows how to use this ‘controller as’ in application:
app.js
-
- var app = angular.module('mainApp', []);
-
-
- app.controller('SimpleCtrl', function ($scope) {
- $scope.name = 'Jeetendra Gund';
- });
-
-
- app.controller('AuthorCtrl', function () {
- this.authorList = ['Vithal Wadje', 'Pankaj Bajaj', 'Rupesh Kahane', 'Nitin Pandit', 'Jasminder Singh'];
- });
The above app.js file we created two controllers, first ‘AuthorCtrl’ for the ‘controller as’ syntax and second ‘SimpleCtrl’ in general we created like.
Index.html
- <!DOCTYPE html>
- <html xmlns="http://www.w3.org/1999/xhtml" ng-app="mainApp">
- <head>
- <title>Welcome to C# Corner</title>
- <script src="app/angular.min.js"></script>
- <script src="app/mainApp.js"></script>
- </head>
- <body>
- <h2>'Controller as' in AngularJS</h2>
- <div ng-controller="SimpleCtrl">
- <h2>By - {{name}}</h2>
- </div>
- <div ng-controller="AuthorCtrl as author">
- <h3>Authors</h3>
- <ul ng-repeat="auth in author.authorList">
- <li>{{auth}}</li>
- </ul>
- </div>
- </body>
- </html>
The above html file we used two created controllers, first ‘SimpleCtrl’ used to display name and second ‘AuthorCtrl’ used to list of authors.
Output:
Great, Controller as syntax in AngularJS with example was created successfully!
Summary
I hope that beginners as well as students understand the concept of Controller as syntax in AngularJS with example. If you have any suggestions regarding this article, then please contact me. Stay tuned for other concepts of AngularJS coming soon!