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?
AngularJS ng-repeat Directive The ng-repeat directive repeats a set of HTML, a given number of times. The set of HTML will be repeated once per item in a collection. The collection must be an array or an object. Note: Each instance of the repetition is given its own scope, which consist of the current item.
"How does this and $scope work in AngularJS controllers?" 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.
$scope is a child object that is used to bind the HTML(view) & Javascript(Controller) in a webpage. It is created with the ng-app directive. It is created with the ng-controller directive.
copy() creates a new object as a deep copy.
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With