1

I am new to Angular and I couldn't get why we assign this to a variable inside the controller.

angular.module('NoteWrangler')
.controller('NoteCreateController', function($http){
    var controller = this;
    this.saveNote = function(note){
        controller.errors = null;
        $http({method: 'POST', url: '/notes', data: note})
        .catch(function(note){
            controller.errors = note.data.error;
        })
    };
});
  • try using `this.errors` inside the callback .... `this` is something completely different there. Has nothing to do with angular, has to do with javascript scoping and closures – charlietfl Oct 03 '15 at 18:31
  • Because `this` is function scoped. So if you want to access the value of `this` in an upper scope, you store it in a variable. – Oriol Oct 03 '15 at 18:32

1 Answers1

0

In general, in Javascript (or other languages) one of the reason "this" is saved like that, is because the value of "this" is not what you expect it to be when other functions in same class/object are invoked. Most of the time when a function is invoked from UI, the value of "this" would be the DOMElement on which the click happened, or the 3rd party object. However you would usually expect that "this" is the object reference because the function belongs to the object.

Value of "this" in Javascript cannot be determined by lexical (by looking at the code structure) scope. Value of "this" is set at runtime depending on how the function in question was invoked.

So essentially you saved a reference to actual "this" so that you can refer to correct object from other functions too.

I highly recommend this book to understand "this": https://github.com/getify/You-Dont-Know-JS/blob/master/this%20&%20object%20prototypes/README.md#you-dont-know-js-this--object-prototypes

TechMaze
  • 447
  • 2
  • 9