Use AngularJS Without $scope

AngularJS 2.0 officially announced in October, 2015. Today, we will discuss about one of the main feature of AngularJS. AngularJS community wanted to remove the $scope objects completely. So before going further, let us discuss how we can use AngularJS without $scope objects.
 
So, if you want to write an angular controller without $scope, then here's the code: 
  1. var angApp = angular.module('angApp',[]);  
  2. angApp.controller('testController', ['$http'function ($http) {  
  3.     var self = this;  
  4.     self.name ='Hello';  
  5.   
  6.     self.btnClick=function(){  
  7.         self.name ='Hello! Button Clicked';  
  8.     }  
  9. }]);  
Here, we declared a var object as self which basically act as a $scope.
 
Now, we need to create a HTML file and link this controller to that html file. The following is the html file code:
  1. <html>  
  2. <head>  
  3. </head>  
  4. <body data-ng-app="angApp" data-ng-controller="testController as model">  
  5. <div>  
  6.     {{model.name}}  
  7.     </br>  
  8.     <input type="button" value="Click" data-ng-click="model.btnClick();"/>  
  9. </div>  
  10. </html>  
Since, in AngularJS file, we didn't used $scope objects, that is why we use controller objects as model objects which directly initialize the controller. Because, like controller command angular already have controller as command. Actually in the above code, we defined the name of the controller instance as model. So any object or method within that controller can be accessed by the model keyword same as object oriented programming. This feature is already available in AngularJS from Angular 1.15. Here are the benefits or work task performance by the conventional $scope objects: 
  1. It communicate between the controller and view.

  2. It sends or receives data between the controller and view.

  3. Pass actions to the view from the controller.

  4. When the $scope object is modified, view automatically changes. Also when user make changes in the View, $scope objects automatically changes.
We define controller as name model. We can assign any name. When page is rendered, AngularJS create the $scope objects internally and assign the attribute and methods of variable so that it acts like $scope.

Up Next
    Ebook Download
    View all
    Learn
    View all