$ scope不在外面工作获取功能

时间:2016-11-18 10:14:48

标签: angularjs

第二个控制台未定义,但第一个工作正常。 以前它工作,不知道它已经停止工作。

angular.module('JobPortal').controller('UserActivityController',function($rootScope, $scope, $http, $timeout,$stateParams,$cookies, UserActivity){

    var token = $cookies.get('token');
    var param ={'token': token};
    UserActivity.user_get(param).success(function(data) {
        $scope.user_id = data._id;
        console.log($scope.user_id);
    });

    console.log($scope.user_id);

    $scope.profileCompletion = function(form) {
        //console.log($scope.user_id);

        var param = $scope.profComp;
        param.user_id = $scope.user_id;
        console.log(param);
        UserActivity.save_details(param).success(function(data) {
            //$scope.lastActivityID = data._id;
            window.location.href = "/vendor#/upload-resume";
        });
    }

});

3 个答案:

答案 0 :(得分:0)

这是因为第二个控制台首先执行。

 angular.module('JobPortal').controller('UserActivityController',function($rootScope, $scope, $http, $timeout,$stateParams,$cookies, UserActivity){



 var token = $cookies.get('token');
    var param ={'token': token};
    UserActivity.user_get(param).success(function(data) {
        $scope.user_id = data._id;
        $scope.consoleUser();
    });

    $scope.consoleUser = function() {
        console.log($scope.user_id);
    }

});

它会起作用

答案 1 :(得分:0)

在您的控制器上保存promise。在$scope.profileCompletion函数内部使用它来确保何时调用该函数它将等待承诺完成(如果它当时没有)。

var promise = UserActivity.user_get(param).success(function(data) {
    $scope.user_id = data._id;
    console.log($scope.user_id);
});

$scope.profileCompletion = function(form) {
    promise.then(function(){
        var param = $scope.profComp;
        param.user_id = $scope.user_id;
        UserActivity.save_details(param).success(function(data) {
            //$scope.lastActivityID = data._id;
            window.location.href = "/vendor#/upload-resume";
        });
    }) 
}

答案 2 :(得分:0)

将代码替换为下面的代码

angular.module('JobPortal').controller('UserActivityController',function($rootScope, $scope, $http, $timeout,$stateParams,$cookies, UserActivity){
     $scope.user_id = "";  //add this line
    var token = $cookies.get('token');
    var param ={'token': token};
    UserActivity.user_get(param).success(function(data) {
        $scope.user_id = data._id;
        console.log($scope.user_id);
    });

    console.log($scope.user_id);

    $scope.profileCompletion = function(form) {
        //console.log($scope.user_id);

        var param = $scope.profComp;
        param.user_id = $scope.user_id;
        console.log(param);
        UserActivity.save_details(param).success(function(data) {
            //$scope.lastActivityID = data._id;
            window.location.href = "/vendor#/upload-resume";
        });
    }

});