AngularJS:在同一个控制器的其他函数中访问作用域

AngularJS: access scope in other function in same controller

本文关键字:函数 访问 作用域 其他 同一个 控制器 AngularJS      更新时间:2023-09-26

我在一个项目中使用角,用户登录后,他的数据被保存到数据库中,他可以传递到主应用程序。但我需要使用他的名字,以显示他的订单,所以我可以提取他的名字,当他登录,但当我想使用这个名字在另一个函数我得到:'未定义'…?

AngularJS

$scope.redirectafterLogin = function($username)
{
    $rootScope.username = $username;
    window.location = "index1.html";
}
//SHOW ORDER FOR LOGGED IN CUSTOMER  
$scope.orderCustomer = function (){
    $http.get('/api/getorderS/'+$rootScope.username).then(function (results) 
    {  
    ... 
    }

那么我如何访问orderCustomer函数中的$rootScope.username变量呢?

您可以将用户名保存在服务中。$scope或$rootScope在进行完全刷新时被鞭打,因为当您"实例化"控制器时,创建了一个范围,当您刷新页面时控制器被重新实例化,因此范围也被鞭打。因此,要创建您的服务,请执行如下操作:

app.factory('userService', [function() {
    return {
        userName: null
    }
}])

,然后在控制器中:

app.controller('loginCtrl', ['userService', function(userService) {
    $scope.redirectafterLogin = function($username)
    {
        userService.userName = $username;
        window.location = "index1.html";
    }
    $scope.orderCustomer = function (){
       $http.get('/api/getorderS/'+ userService.userName).then(function (results) 
       {  
            ... 
       }

你也可以用getter和setter来美化上面的代码,只需添加:

setUserName: function(user) {
        this.userName = user;
     },
getUserName: function() {
        return this.userName;
}

到您的服务,然后用+ userService.getUserName()替换+ userService.username

编辑顺便说一句:确保你在'index1.html'中使用ng-controller="loginCtrl" !