Federick Jons Federick Jons - 1 month ago 7
AngularJS Question

Angular: Using "this" instead of " $scope" in "Controller As"

I want to use "this" instead of $scope because I have a controller structure that doesn't initialize $scope:

.controller('MyCtrl', function($scope) {
...
});


I must follow a tutorial with the structure above and put the $scope service to make it work.

Controller

(function() {
'use strict';

angular
.module('example.cancha')
.controller('CanchaController', CanchaController);

CanchaController.$inject = ['$state','$scope', 'canchaService'];

function CanchaController($state, $scope, canchaService) {
var vm = angular.extend(this, {
canchasComplejo: []
});



(function activate() {
cargarCanchasComplejo();

})();

//funcion que llama al servicio para obtener las canchas del complejo
function cargarCanchasComplejo() {
canchaService.obtenerCanchasComplejo()
.then(function(canchasComplejo) {
vm.canchasComplejo = canchasComplejo;
$scope.groups = [];
for (var i=0; i<canchasComplejo.length; i++) {
$scope.groups[i] = {
name: 'Cancha N°'+canchasComplejo[i].nroCancha+' ('+canchasComplejo[i].tipoCancha+')',
items: ['Información','Habilitada','Ver Agenda'],
show: false
}
};

$scope.toggleGroup = function(group) {
group.show = !group.show;
};
$scope.isGroupShown = function(group) {
return group.show;
};
});
}
}
})();


As you can see, this is not the regular structure. Can I avoid using $scope using "this"? Thanks!

Answer

remove $scope injection from your controller:

CanchaController.$inject = ['$state','$scope', 'canchaService'];
function CanchaController($state, $scope, canchaService) {
  .....

should be:

CanchaController.$inject = ['$state', 'canchaService'];
function CanchaController($state, canchaService) {

then replace all $scope occurrences within controller scope with vm: $scope.groups = []; becomes vm.groups = [];

now be aware that in the HTML using this controller you cannot access groups directly, but you should use ng-controller="CanchaController as vm" (free fill to use any name instead of vm) and access groups with vm.groups. Your HTML might look like:

<div ng-controller="CanchaController as vm">
  <pre>{{ vm.groups | json }}</pre>
</div>

if this controller is used with routing or directive, then controllerAs: 'vm' should be set on JS level and not HTML

Comments