即使在分配

时间:2016-03-06 12:35:59

标签: javascript angularjs

我的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>

对我而言,这似乎应该有效 - 看起来很简单。

1 个答案:

答案 0 :(得分:0)

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>