10

I'm new to angularjs. What is the difference if You assign function to $scope or this keywords in the controller? Thank You.

Example (scope):

.controller('TestCtrl', ['$scope', function ($scope) {
    $scope.testFunc = function () {
    };
}]);

Example (this)

.controller('TestCtrl', [function () {
    var app = this;
    app.testFunc = function () {
    };
}]);

2 Answers 2

10

$scope is a core concept of angular framework and dual data-binding functionnalities. Its for example, designed to share its content with :

  • templates
  • directives
  • etc

In a template for example, you'll need to bind a function to the scope to access it. You'll not be able to call a function binded on this directly.


Edit: Thank to BKM post that pointed out that this behavior is possible with the "controller as" syntax which binds your template directly to the controller. But it's up to you to decide if you want to let access all objects/variables of your controller in your template instead of having a dedicated viewModel (scope). For pros and cons, see : https://groups.google.com/forum/#!topic/angular/84selECbp1I


It's an important concept of angular that you need to understand.

See :

this keywork refers only the the javascript object refering to your controller, nothing more.

8

What Bixi said was wrong. It isn't necessary to have a function bind to the scope inorder to access it.

In the newest version of Angular JS i.e, 1.2 they have introduces a new keyword controllerAs to make it possible not to have scope inside a controller.

<div ng-controller="testCtrl as test">
    {{test.value}}
</div>

And in your controller

app.controller('testCtrl ', function () {
   this.value = 'Hello World';
});

See the above controller is generated with out injecting $scope in it.

Here is a good video tutorial explaining this

1
  • @BKM that was exactly the tutorial I have watched and saw this concept so I needed clarification for it. Thank You for Your answers guys, cheers! ;)
    – Johny Boy
    Commented Aug 11, 2014 at 14:05

Your Answer

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

Not the answer you're looking for? Browse other questions tagged or ask your own question.