neridaj
neridaj

Reputation: 2183

AngularJS controller as syntax "this" is not $scope

I'm new to angularjs and I'm trying to employ the styles outlined from this post: https://github.com/johnpapa/angular-styleguide. When using the var vm = this style, rather than $scope, the vars I'm trying to bind to in the template are unavailable. Inspecting vm in the console shows an empty object, not the same as $scope.

/* index.js */

angular.module('myApp', ['ngAnimate', 'ngCookies', 'ngTouch', 'ngSanitize', 'ngResource', 'ngRoute', 'ui.bootstrap', 'loginModule', 'sidebarModule', 'jm.i18next'])
.value('baseUri', "/myApp/api")
.config(config)
.run(function($rootScope, $injector) { 
  $injector.get("$http").defaults.transformRequest = function(data, headersGetter) { 
      if ($rootScope.oauth !== undefined) {
        console.log($rootScope.oauth);
        headersGetter()['Access-Token'] = $rootScope.oauth.access_token; 
      }
      if (data) { 
          return angular.toJson(data);
      } 
  }; 
});

function config($routeProvider, $i18nextProvider) {
  $routeProvider
    .when('/', {
      templateUrl: 'app/my-module-login/login.html',
      controller: 'loginController',
      conrollerAs: 'vm' // not available in template
    })
    .otherwise({
      redirectTo: '/'
    });

/* login.module.js */

angular.module('loginModule', ['utils']);

/* login.controller.js */

(function(){
'use strict';

angular.module('loginModule')
.controller('loginController', login);

login.$inject = ['$rootScope', '$scope', 'credsFactory', 'loginFactory'];

function login($rootScope, $scope, credsFactory, loginFactory) {

    var vm = this; //empty object
    vm.user = {};
    vm.login = doLogin;

    function doLogin(user) {
        //user creds
        var creds = {
            userName: user.username,
            password: user.password
        };

        loginFactory.login(creds)
            .success(function (data) {
                credsFactory.setCreds(data);
                $scope.status = 'Logged in user!';
                $scope.creds = creds;
                var storageCreds = credsFactory.getCreds();
                $rootScope.oauth = {};
                $rootScope.oauth.access_token = storageCreds.accessToken;
                window.location.hash = "#/logged-in";
            }).
            error(function(error) {
                $scope.status = 'Unable to login user: ' + error.message;
            });
    }

}

})();

/* login.html */

        <div class="form-group form-group-sm">
            <div class="text-center">
                <!-- how to access vm, {{vm.login(user)}} doesn't work -->
                <button type="button" class="btn btn-default" id="login-submit" ng-i18next="button.cancel" ng-click="login(user)"></button>
            </div>
        </div>

Upvotes: 1

Views: 451

Answers (1)

kodknackare
kodknackare

Reputation: 71

You can declare the controllerAs when setting up the route - there is a typo in your example. (The name does not have to be the same as in loginController function)

Route:

$routeProvider
    .when('/', {
       templateUrl: 'app/my-module-login/login.html',
       controller: 'loginController',
       controllerAs: 'vm'
    })

View:

<button ng-click="vm.login(user)"></button>

Also, when using "var vm = this;" in the controller function, you do not need to inject $scope. Instead of $scope in doLogin success function:

vm.status = 'Logged in user!';

Upvotes: 1

Related Questions