AngularJS承诺的可变范围问题

时间:2015-11-14 11:08:18

标签: javascript angularjs

我是AngularJS的全新人,我试图找出我的代码有什么问题。

一般来说,它看起来是一个可变范围问题,但我不知道如何解决它:

这是我的代码:

'use strict';

(
    function() {
        /**
         * @name angularApp.controller:LoginpageCtrl
         * @description This controller is responsible to manipulate the user login process.
         * @param themeConfigs Contains the site themeConfiguration options.
         */
        var $userRegisterCtrl = function ( $window, $timeout, user, themeConfigs ) {
            var $this = this;
            $this.theme_configs = themeConfigs;
            $this.username = '';
            $this.email = '';
            $this.password = '';
            $this.error = '';
            $this.success = '';

            $this.register = function() {
                user
                    .register(
                        $this.username,
                        $this.password,
                        $this.email
                    )
                    .then(
                        function( ) {
                            $this.success = 'Your account has been successfully created.<br />';
                            $this.success += 'Soon you will redirected in login page.';

                            $timeout(
                                function() {
                                    $window.location.href = '/#/login';
                                },
                                4000
                            );
                        },
                        function( $error_message ) {
                            console.log( $error_message );
                        }
                    );
            };
        };

        $userRegisterCtrl.$inject = [ '$window', '$timeout', 'user', 'themeConfigs' ];

        angular.module('angularApp' ).controller( 'userRegisterCtrl', $userRegisterCtrl );
    }
)();

我得到的错误如下:

TypeError: Cannot set property 'success' of undefined
    at register.js:27
    at processQueue (angular.js:14745)
    at angular.js:14761
    at Scope.parent.$get.Scope.$eval (angular.js:15989)
    at Scope.parent.$get.Scope.$digest (angular.js:15800)
    at Scope.parent.$get.Scope.$apply (angular.js:16097)
    at done (angular.js:10546)
    at completeRequest (angular.js:10744)
    at XMLHttpRequest.requestLoaded (angular.js:10685)

所以第27行与以下两行有关:

$this.success = 'Your account has been successfully created.<br />';
$this.success += 'Soon you will redirected in login page.';

但为什么$ this.success超出范围?我该如何解决这个问题?有没有与promisses相关的技巧?

1 个答案:

答案 0 :(得分:1)

你可以尝试将$ this重命名为_this吗?通常angular使用$作为其服务和变量,

  • $索引
  • $ ID
  • $这

所有例子

您的问题与范围变量无关,但未定义$。