this vs $scope in angular.js? [duplicate] this vs $scope in angular.js? [duplicate] ruby-on-rails ruby-on-rails

this vs $scope in angular.js? [duplicate]


The function you put into angular.controller is used as a constructor. JavaScript constructors that return nothing, implicitly return this. If a constructor returns another object, then this object is supposed to be the new object. e.g.:

function Class1() {    this.prop = 'xxx';}var obj1 = new Class1();console.log(obj1.prop); // prints 'xxx'function Class2() {    this.prop = 'xxx';    return {        hooray: 'yyy'    };}var obj2 = new Class2();console.log(obj2.prop); // prints undefinedconsole.log(obj2.hooray); // prints 'yyy'

Your controller returns an http promise (the return value of $http.get(...).success(...)), so angular believes that this (the http promise) is your actual controller (the thing it assigns to $scope.labCtrl).

No time to test it, hope I got it right.

Tiny example here


You assigned a value to this.laboratorios inside a closure. Remember that its scope is separated from the outer scope. this applies to something completely different. This is why using $scope is more reliable (and readable, if you ask my personal opinion). You might want to bind the closure to a this value:

(function() {    var app = angular.module('guiaV', []);    app.controller('LaboratorioController', function( $http) {      this.laboratorios = [];      $http.get('./laboratorios.json').success(function(data) {        return this.laboratorios = data;      }.bind(this));    });})();

Alternatively, you can use a variable that will be available from both scopes:

(function() {    var app = angular.module('guiaV', []);    app.controller('LaboratorioController', function( $http) {      this.laboratorios = [];      var foo = this;      $http.get('./laboratorios.json').success(function(data) {        return foo.laboratorios = data;      });    });})();