AngularJS:在AJAX调用后将变量分配给$ scope

时间:2014-05-11 14:30:20

标签: angularjs

我太近了,我闻到了终点线 -

当我的应用程序启动时,我从用户那里收集登录信息(这是一个AngularJS SPA,所以我可以从spInfoContext轻松获取),我通过搜索名为的列表来查看用户是否是返回用户itiUsers 用于userId。如果没有找到记录,我会立即在 itiUsers 中创建一条新记录,然后为新用户提供一个表单,以输入我无法从SharePoint获取的信息。记录已正确创建。当promise返回时,我正在尝试填充$ scope.current_user对象,以便它与返回的用户一样 - 这样我只需要一个My Preferences表单。

但是,当我在创建记录后注销$ scope时,current_user为空。

这是我的控制器功能(我为了简洁而减少了值,我试图加粗问题线):

$.when(SharePointJSOMService.getCurrentUser())
    .done(function(jsonObject){
        if(jsonObject.d.results.length < 1 || jsonObject.d.results.newUser ){
        // new user
        $.when(SharePointJSOMService.getLoggedInUser())
            .done(function(jsonObject){
            $scope.loggedInUser = jsonObject.d;
            $scope.isNewUser = true;
            $.when(SharePointJSOMService.createNewUser($scope))
                .done(function(jsonObject){
                **$scope.current_user.DisplayName = $scope.loggedInUser.Title;
                              console.log($scope);**
                })
                .fail(function(err){
                $scope.prefPane = true;
                console.info(JSON.stringify(err)); 
            });
            })
            .fail(function(err){
            $scope.prefPane = true;
            console.info(JSON.stringify(err)); 
            });
            $scope.prefPane = true; // force preference pane
            $scope.taskClose = true;
            $scope.$apply();
        } else {
            // existing user
            $scope.isNewUser = false;
            $scope.prefPane = false; // hide preference pane
            $scope.current_user = jsonObject.d.results[0];
            switch($scope.current_user.Role){
                case 'USR':
                $scope.projectClose = 'true';
                break;
                case 'PMG':
                $scope.projectClose = 'false';
                break;
            default:
                $scope.projectClose = 'true';
                break;
             } // end switch
             $scope.$apply();
            } // end if
        })
        .fail(function(err){
             $scope.prefPane = true;
             console.info(JSON.stringify(err)); 
        });

1 个答案:

答案 0 :(得分:0)

崩溃是因为您在创建新用户后尝试设置$scope.current_user.DisplayName但未定义$ scope.current_user对象。请尝试改为:

$scope.current_user = {
   DisplayName: $scope.loggedInUser.Title
}