Difference between this and $scope in Controller in AngularJS

Last Reply 4 months ago By dharmendr

Posted 4 months ago

What is the difference between this and $scope in controllers in AngularJS and what is track by and how does it work?

Posted 4 months ago Modified on 4 months ago

Hi rani,

Check this example.

This and $scope

HTML

<html xmlns="http://www.w3.org/1999/xhtml">
<head>
    <title></title>
    <script type="text/javascript" src="https://cdnjs.cloudflare.com/ajax/libs/angular.js/1.7.8/angular.min.js"></script>
    <script type="text/javascript">
        var app = angular.module('MyApp', []);
        app.controller("MyController", function ($scope) {
            this.title = 'Some title';
        });
        app.controller("MyController1", function ($scope) {
            $scope.title = 'Some title';
        });    
    </script>
</head>
<body ng-app="MyApp">
    <div ng-controller="MyController as main">
        {{main.title}}
    </div>
    <hr />
    <div ng-controller="MyController1">
        {{title}}
    </div>
</body>
</html>

Demo

Refer below links for more details.

https://stackoverflow.com/questions/22806681/difference-between-this-and-scope-in-the-controller

https://stackoverflow.com/questions/11605917/this-vs-scope-in-angularjs-controllers

https://ultimatecourses.com/blog/digging-into-angulars-controller-as-syntax

track by 

track by basically tell angular to generate a single DOM element per data object in the given collection. 

You can track by $index if your data source has duplicate identifiers. 

If you do need to repeat duplicate items, you can substitute the default tracking behavior with your own using the track by expression. 

Refer below link for example. 

Display categorized filter data in HTML Table using AngularJS

Refer below link for more details.

https://www.c-sharpcorner.com/blogs/use-of-track-by-in-angular-js