AngularJS控制器作为语法“this”不是$ scope

时间:2015-03-18 20:58:12

标签: angularjs angularjs-scope

我是angularjs的新手,我正在尝试使用这篇文章中概述的样式:https://github.com/johnpapa/angular-styleguide。当使用var vm = this样式而不是$ scope时,我试图在模板中绑定的变量不可用。在控制台中检查vm会显示一个空对象,与$ 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>

1 个答案:

答案 0 :(得分:1)

您可以在设置路线时声明 controllerAs - 您的示例中存在拼写错误。 (名称不必与loginController函数中的名称相同)

路线:

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

查看:

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

另外,使用“var vm = this;”时在控制器功能中,您不需要注入$ scope。而不是doLogin成功函数中的$ scope:

vm.status = 'Logged in user!';