Skip to content Skip to sidebar Skip to footer

Confusion About 'this' Keyword In Angular 'controller As' Syntax

I have a parent controller, UserEditCtrl and a child controller, EditUserCtrl. Inside of my parent controller I am pulling in a user object via a service: userMgmtSvc.user(scope.ed

Solution 1:

This is a very basic mistake that happens when you refer to the current context with this inside a callback about which you don't know about the execution context and you end up setting values elsewhere.

In order to avoid getting into this issue, when your controller starts just set this (context of controller instance) to a variable and set everything on that. Don't assume what this is going to be.

 .controller('crtl',[deps..., function(...) {
       //Set thisvar vm = this; //Always use this cached variable have seen a commonly used name of vm//............... //...............
       userMgmtSvc.user(scope.editUserId).then(function(data) {
         vm.user = data;
       });

       //...............
       vm.selectedRoles = vm.user.roles

   }

There are numerous other ways to do this using angular.bind, or es5 function.bind to create a bound functions (function reference pre bound with a specified context), but easiest way would be to use a cached context.

When you are using typescript you could use a => (fat arrow) syntax since typescript in ES5 mode will actually convert this.

      userMgmtSvc.user(scope.editUserId).then((data) => {
         this.user = data;
      });

to:-

var _that = this;
    userMgmtSvc.user(scope.editUserId).then((data) => {
         _that.user = data;
     });

Arrow functions are going to be part of the language itself (with ES6 specifications) when the engines starts supporting the arrow function syntax. So with ES6 you could safely write:-

      userMgmtSvc.user(scope.editUserId).then((data) => {
         this.user = data;
      });

Here is an excellent answer that specifically targets this

Post a Comment for "Confusion About 'this' Keyword In Angular 'controller As' Syntax"