this vs $scope in angular.js?

angularjs, javascript, ruby-on-rails

Solution

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 undefined
console.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

Problem

I'm developing a rails app with angular, and in the past, I had been using $scope to access variables and methods of the angular's controllers. After watching the Shaping up with Angular.js course at codeschool, I realized that the usage of this and the alias of controllers are a better way of accessing them. Anyway, my app works fine with $scope but when I change to the "this" implementation, the laboratories var came empty... I let some code here: html: ``` <div ng-controller="LaboratorioController as labCtrl"> <tr ng-repeat="laboratorio in labCtrl.laboratorios" > <td>{{ laboratorio.nombre }}</td> <td>{{ laboratorio.razon_social }}</td> <td>{{ laboratorio.direccion }}</td> ``` angular code: ``` (function() { var app = angular.module('guiaV', []); app.controller('LaboratorioController', function( $http) { this.laboratorios = []; return $http.get('./laboratorios.json').success(function(data) { return this.laboratorios = data; }); }); })(); ``` any idea?

Original source

Related problems