We can communicate with HTML DOM using $scope variable in AngularJS, but it’s not hard and fast rule to use scope to communicate with View, we can also create controller without using $scope and use all the properties and behavior in view (HTML).
Why scope-less controller
Sometimes controller become complex by using $scope for providing data and behavior to view, in that situation we can use scopeless controller.
But if you have designed your AngularJS application perfectly, there is no need to go for scopeless controllers.
Creating scope-less controller
- angular module(app.js):
- angular.module('myApp', []);
Controller (homeController.js) - var app = angular.module("myApp");
-
- app.controller("myController", function ()
- {
-
- this.title = 'scopeless Controller Test';
- this.name = 'Anupam';
- this.sayHello = function ()
- {
- alert('Hello ' + this.name);
- }
-
- });
As you can see I have used javaScrip
this keyword to add data and behavior in my controller.
I would love to explain
this here but I am still in a way to explore what is
this in JavaScript.
Here is how we can get data from controller to view.
Binding Data to View using scope-less controller View (index.html) - <!DOCTYPE html>
- <html ng-app="myApp" ng-controller="myController as ctrl">
-
- <head>
- <script src="Scripts/angular.min.js"></script>
- <script src="app/app.js"></script>
- <script src="app/homeController.js"></script>
- <link href="Css/bootstrap.min.css" rel="stylesheet" />
- <title>{{ctrl.title}}</title>
- </head>
-
- <body>
- <nav role="navigation" class=" navbar navbar-default">
- <div class="navbar-header">
- <a href="#" class="navbar-brand">
- {{ctrl.title}}
- </a>
- </div>
-
- </nav>
- <div class="container body-content">
- <div class="col md-6">
- <div class="row">
- <div class="well-lg">
- Hi {{ctrl.name}}
- </div>
- </div>
- <div class="row">
- <div class="well-lg">
- <input type="button" ng-click="ctrl.sayHello()" value="Say Hello" class="btn" />
- </div>
- </div>
- </div>
- </div>
- </body>
-
- </html>
Here I have used a variable ctrl (
myController as ctrl) which is an instance of
myController.
Note: We have to create a variable using as keyword, since we can’t access controller using its name. For example: we can’t access name property using
myController.name in view.
Summary
In this article we learned how we can communicate between view and controller without using $scope variable. I have also attached sample code if you wish to download. Hope you enjoyed this.