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:
- var angApp = angular.module('angApp',[]);
- angApp.controller('testController', ['$http', function ($http) {
- var self = this;
- self.name ='Hello';
-
- self.btnClick=function(){
- self.name ='Hello! Button Clicked';
- }
- }]);
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:
- <html>
- <head>
- </head>
- <body data-ng-app="angApp" data-ng-controller="testController as model">
- <div>
- {{model.name}}
- </br>
- <input type="button" value="Click" data-ng-click="model.btnClick();"/>
- </div>
- </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:
- It communicate between the controller and view.
- It sends or receives data between the controller and view.
- Pass actions to the view from the controller.
- 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.