Oliver
Oliver

Reputation: 1644

Angular JS - What is '$scope' and how does it compare to using the 'this' keyword?

I am new to Angular JS and have been taught it the 'this' way:

<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>
<script>
    var app = angular.module('Comment',[]);
    app.controller('CommentCtrl',function(){
        this.welcome = 'Hello!';
    });
</script>
<p ng-app='Comment' ng-controller='CommentCtrl as ctrl'>
    Angular says: {{ ctrl.welcome }}
</p>

Which shows 'Angular says: Hello!' inside the paragraph.

However, every angular application I have ever seen has used '$scope' instead of 'this', like I was taught.

Could someone please explain a few of the pros and cons of each, and what exactly $scope is in terms that I can understand?

Thanks.

Upvotes: 0

Views: 141

Answers (1)

Zeeshan Hassan Memon
Zeeshan Hassan Memon

Reputation: 8325

Some Good Points:

  • this
    • When the controller constructor function is called, this is the controller.
    • When a function defined on a $scope object is called, this is the "scope in effect when the function was called". This may (or may not!) be the $scope that the function is defined on. So, inside the function, this and $scope may not be the same.
  • $scope
    • Every controller has an associated $scope object.
    • A controller (constructor) function is responsible for setting model properties and functions/behavior on its associated $scope.
    • Only methods defined on this $scope object (and parent scope objects, if prototypical inheritance is in play) are accessible from the HTML/view. E.g., from ng-click, filters, etc.

Here is cool article by Todd Motto

Happy Helping!

Upvotes: 3

Related Questions