Angularjs属性在控制器中未定义

时间:2017-10-09 01:45:01

标签: angularjs

尝试通过电子邮件重置密码。单击电子邮件中的重置链接并指向重置页面后,控制台可以输出“$ scope.username”值,但是在下一行右侧会抛出错误,因为“用户名”未定义。 Error Screenshot

不确定哪里出错了。感谢。

.controller('resetCtrl', function(User, $routeParams, $scope, $timeout, $location) {

    app = this;
    app.hide = true; 

    User.resetUser($routeParams.token).then(function(data) {
        if (data.data.success) {
            app.hide = false; 
            app.successMsg = 'Please enter a new password'; 
            $scope.username = data.data.user.username; 
        } else {
            app.errorMsg = data.data.message; 
        }
    });

    app.savePassword = function(regData, valid, confirmed) {
        app.errorMsg = false;
        app.disabled = true; 
        app.loading = true; 
        console.log($scope.username); // test output
        app.regData.username = $scope.username; 
            User.savePassword(app.regData).then(function(data) {
                app.loading = false; 
                if (data.data.success) {
                    app.successMsg = data.data.message + '...Redirecting'; 
                    $timeout(function() {
                        $location.path('/login');
                    }, 2000);
                } else {
                    app.disabled = false; 
                    app.errorMsg = data.data.message; 
                }
            });
        }
});

1 个答案:

答案 0 :(得分:1)

在外面声明 $scope.username ,这将解决您的问题,因为您使用控制器作为语法,最好将其作为app.username。

.controller('resetCtrl', function(User, $routeParams, $scope, $timeout, $location) {

    app = this;
    app.hide = true; 
    app.username = '';
    User.resetUser($routeParams.token).then(function(data) {
        if (data.data.success) {
            app.hide = false; 
            app.successMsg = 'Please enter a new password'; 
            app.username = data.data.user.username; 
        } else {
            app.errorMsg = data.data.message; 
        }
    });

    app.savePassword = function(regData, valid, confirmed) {
        app.errorMsg = false;
        app.disabled = true; 
        app.loading = true; 

        app.regData.username = app.username; 
            User.savePassword(app.regData).then(function(data) {
                app.loading = false; 
                if (data.data.success) {
                    app.successMsg = data.data.message + '...Redirecting'; 
                    $timeout(function() {
                        $location.path('/login');
                    }, 2000);
                } else {
                    app.disabled = false; 
                    app.errorMsg = data.data.message; 
                }
            });
        }
});