0

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.

2
  • What's wrong with my question? It took a lot of effort to get my reputation. Please don't just take it off me. Commented Mar 24, 2015 at 22:47
  • The "controller as" functionality is a fairly recent addition to angularjs hence the reason that most tutorials use $scope. I have a read a few articles that suggest the angularjs 2.0 will not use $scope. Commented Mar 25, 2015 at 1:05

1 Answer 1

3

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!

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.