$ scope variable即使在赋值后也未定义

问题描述:

我在我的一个Angular控制器中有函数,我遇到了一个问题。

在函数的开始处,我尝试检查是否提供了出发时间,如果没有提供出发时间,我以HH:mm:ss格式为其分配当前时间。

但是,当我尝试检查值$ scope.selectedDepartureTime.departureTime甚至在赋值后,它仍然是未定义的。为什么?

$scope.search = function() { 
    if (!$scope.selectedDepartureTime.departureTime) { 
     var time = new Date(); 

     var departureTime = 
      ("0" + time.getHours()).slice(-2) + ":" + 
      ("0" + time.getMinutes()).slice(-2) + ":" + 
      ("0" + time.getSeconds()).slice(-2); 

     //12:32:15 app.js:80 
     console.log(departureTime); 

     $scope.selectedDepartureTime.departureTime = 
      departureTime; 
     //undefined app.js:85 
     console.log($scope.selectedDepartureTime.departureTime); 
    } 

    $http({ 
     method: 'GET', 
     url: '/train-times/journey?departureStation=' 
     + $scope.selectedDepartureStation.stationName 
     + '&destinationStation=' 
     + $scope.selectedDestinationStation.stationName 
     + '&queryTime=' 
     + $scope.selectedDepartureTime.departureTime, 
     data: {} 
    }).success(function (result) { 
     $scope.journeyResult = result; 
    }); 

    $http({ 
     method: 'GET', 
     url: '/train-times/departure-times?departureStation=' 
     + $scope.selectedDepartureStation.stationName 
     + '&queryTime=' 
     + $scope.selectedDepartureTime.departureTime, 
     data: {} 
    }).success(function (result) { 
     $scope.otherDepartureTimes = result; 
    }); 
} 

数据从一个HTML表单提交:

<label for="departAfter">Depart after:</label> 
<select id="departAfter" 
    ng-model="selectedDepartureTime" 
    ng-options="time.departureTime for time in departureTimes" 
    ng-init="selectedDepartureTime='undefined'"> 
</select> 

对我来说,这似乎像它应该工作 - 似乎很简单。

+0

很难判断您发布的信息有什么问题。 80和85线是什么? – Chanthu

+0

第80行和第85行是console.log语句。 – moka

+1

你在哪里初始化$ scope.selectedDepartureTime? – Ricky

undefined更改为{}

<label for="departAfter">Depart after:</label> 
<select id="departAfter" 
    ng-model="selectedDepartureTime" 
    ng-options="time.departureTime for time in departureTimes" 
    ng-init="selectedDepartureTime={}"> <!-- Change undefined to {}--> 
</select>