user3616799
user3616799

Reputation: 3

Correct Way to Use this in a controller

I heard in a blog that an easy way to prepare for Angular 2.0 is to not use $scope inside a controller, but use this instead. I have found that this used inside a function that is inside a controller is not the this that should be the $scope

FAILS

var loginControllerId = 'loginCtrl';
app.controller(loginControllerId, ['$scope',function ($scope) {
    this.login = {};
    function myFunc(){
        // FAILS - this.login is undefined I think because "this" is now referring to the myFunc function
        this.login.message = "Some Message"; 
    }
    this.login.successMessage = "Success";  // PASSES        
});

What I think is a work around is to create a var and set this ($scope) to it. Can somebody tell me if this is a good way to do this or if there is a different method to globally use the controllers this?

PASSES

var loginControllerId = 'loginCtrl';
app.controller(loginControllerId, ['$scope',function ($scope) {
    var loginScope = this;
    loginScope.login = {};
    function myFunc(){
        // PASSES
        loginScope.login.message = "Some Message"; 
    }
    loginScope.login.successMessage = "Success";  // PASSES        
});

Upvotes: 0

Views: 37

Answers (2)

jstuartmilne
jstuartmilne

Reputation: 4488

Another way is to use angular extend

function MainCtrl () {
  angular.extend(this, {
    someVar: {
      name: 'Todd'
    },
    anotherVar: [],
    doSomething: function doSomething() {

    }
  });
}

Take a look at this post for full explanation

https://toddmotto.com/a-better-way-to-scope-angular-extend-no-more-vm-this/

Upvotes: 1

CMR
CMR

Reputation: 933

Its common to use something like var vm = this; in your controller. See the very popular styleguide by John Papa.

Upvotes: 2

Related Questions