调用数据服务后,变量的值变为未定义

时间:2015-04-19 09:36:21

标签: angularjs angularjs-controller

我有一个角度js控制器' TakeSurveyController'它调用数据服务“takeSurveyDataService'”。控制器有一个变量empId,我使用'这个'关键词。但是,在调用数据服务后,此变量的值很快就会变为未定义。

(function(){
dataUrls = {

    employeeUrl : '/SurveyPortal/Company/Employees/'    
}

angular.module('takeSurvey',[])
.service('takeSurveyDataService',function($http,$log){
    this.checkEmployee = function(employeeId){
        var url = dataUrls.employeeUrl + employeeId;
        return $http.get(url);
    };

})
.controller('TakeSurveyController',function($http,takeSurveyDataService,$location){
    this.empId = '';
    this.checkEmployee = function(){
        takeSurveyDataService.checkEmployee(this.empId).then(this.attemptSurvey);//empId has value here. Call successful to data service
    };
    this.attemptSurvey = function(employeeResponse) {
        if(employeeResponse.data=="true"){
            $location.path('/attemptSurvey/'+this.empId); //empId variable undefined here, unable to access value that was available above

        }
        else{
            this.empId = '';
            alert("This empId has not been registered. Please register before taking survey!");
        }

    };
})
})();

以下是html代码。

<!DOCTYPE html>
<html>
<head>
<meta charset="ISO-8859-1">
<title>Insert title here</title>
</head>
<body>
<div align="center" style="margin-top:50px">
    <form name="checkEmployee" ng-controller="TakeSurveyController as takeSurveyController" ng-submit="takeSurveyController.checkEmployee()" >
        <input type="text" ng-model="takeSurveyController.empId" placeholder="Employee ID" /><br>
        <input type="submit" class="btn btn-large btn-success" value="Move to survey" />
    </form>
</div>
</body>
</html>

1 个答案:

答案 0 :(得分:1)

你必须非常小心地使用这个内部函数,因为'this'这个词每次都有不同的含义,具体取决于上下文。我相信在承诺回调'这'得到了不同的含义,它与TakeSurveyController失去联系。请尝试将'this'指定给'self'变量,这在angular和js中总是很好的做法:

(function(){
dataUrls = {

    employeeUrl : '/SurveyPortal/Company/Employees/'    
}

angular.module('takeSurvey',[])
.service('takeSurveyDataService',function($http,$log){
    var self = this;
    self.checkEmployee = function(employeeId){
        var url = dataUrls.employeeUrl + employeeId;
        return $http.get(url);
    };

})
.controller('TakeSurveyController',function($http,takeSurveyDataService,$location){
    var self = this;
    self.empId = '';
    self.checkEmployee = function(){
        takeSurveyDataService.checkEmployee(self.empId).then(self.attemptSurvey);//empId has value here. Call successful to data service
    };
    self.attemptSurvey = function(employeeResponse) {
        if(employeeResponse.data=="true"){
            $location.path('/attemptSurvey/'+self.empId); //empId variable undefined here, unable to access value that was available above

        }
        else{
            self.empId = '';
            alert("This empId has not been registered. Please register before taking survey!");
        }

    };
})
})();