Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Difference between this and scope in the controller

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 () {
    };
}]);
like image 322
Johny Boy Avatar asked Apr 02 '14 09:04

Johny Boy


People also ask

What is controller scope?

The scope is the binding part between the HTML (view) and the JavaScript (controller). The scope is an object with the available properties and methods. The scope is available for both the view and the controller.

What is the difference between the scopes of a directive and the scopes of a controller?

No difference. It is same object.

What is $scope vs 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.

What is the difference between $scope and scope?

In short, in case of dependency injection the scope object is received as $scope while in case of non-dependency injection scope object is received as scope or with any name. Save this answer.


1 Answers

$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 :

  • http://docs.angularjs.org/guide/scope for an introduction
  • https://github.com/angular/angular.js/wiki/Understanding-Scopes for more technical information about scopes

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

like image 181
Jscti Avatar answered Sep 29 '22 02:09

Jscti