2016-08-25 80 views
1

我想填充選項而不是未定義的值,但似乎在選擇框完成加載後繼續獲取值。

Several items, but all undefined.

HTML:

<label for="to">Destination: 
    <select id="to" name="to" ng-model="toSelected" data-ng-options="stop.stop_id as stop.name for stop in stops"> 
     <option value="">Choose a Destination</option> 
    </select> 
    </label> 

AngularJS廠:

.factory('DataFactory', ['$http', function ($http) { 


// Might use a resource here that returns a JSON array 
return { 

    getAllStops: function() { 
    return $http({ 
     method: 'GET', 
     url: 'https://myAPIURL.com/api', 
     headers: { 
     "Accept": "application/json", 
     "X-Mashape-Key": "KEYKEYKEYKEYKEYKEYKEYKEYKEYKEYKEY" 
     } 
    }).then(function (res) { 
     return res; 
    }) 
    }, 
     getAllRoutes: function() { 
     return someresult similar to the above function; 
    // more functions. 
    } 

AngularJS控制器:

.controller('MainCtrl', ['$scope', '$http', '_', 'DataFactory', function ($scope, $http, _, DataFactory) { 

$scope.fromSelected = ""; 
$scope.toSelected = ""; 

DataFactory.getAllStops().then(function successCallback(res) { 
    console.log(res); 
    $scope.stops = res.data; 

}, function errorCallback(err) { 
    console.log("error: "); 
    console.log(err); 
}); 

$scope.changed = function (location, destination) { 
console.log($scope.stops); 
    $scope.possibleRoutes = DataFactory.getPossibleRoutes(location, destination); 

回答

2

您的工廠在您的工廠未按預期返回承諾。從工廠中取出,然後「那麼」作爲跟隨返回一個承諾,或http請求:

.factory('DataFactory', ['$http', function ($http) { 


// Might use a resource here that returns a JSON array 
return { 

    getAllStops: function() { 
    return $http({ 
     method: 'GET', 
     url: 'https://myAPIURL.com/api', 
     headers: { 
     "Accept": "application/json", 
     "X-Mashape-Key": "KEYKEYKEYKEYKEYKEYKEYKEYKEYKEYKEY" 
     } 
    }) 
    }, 
     getAllRoutes: function() { 
     return someresult similar to the above function; 
    // more functions. 
    } 

控制器處理正確一旦做出更改假設你得到響應的承諾。

另外,驗證「stop_id」是否在實際響應中。與......相反,stopID或其他東西。如果stopID存在,但是您拉動stop.stop_id,則它將顯示爲未定義。

+0

「另外,請驗證」stop_id「是否在實際響應中,而不是...... stopID或其他,如果stopID存在,但是您拉動stop.stop_id,它將顯示爲未定義。 關閉。它增加了一個額外的深度,這很奇怪。我必須做res.data.data才能達到我需要的。 –

2

考慮初始化帶有佔位符數據的(即$scope.stops = [{stop_id: false, name: 'Loading'}]

或者,您可以使用ng-if在數據完成加載時加載選擇框。

Ex。

<div class="input" ng-if="stops"> 
    <label for="to">Destination: 
    <select id="to" name="to" ng-model="toSelected" data-ng-options="stop.stop_id as stop.name for stop in stops"> 
     <option value="">Choose a Destination</option> 
    </select> 
    </label> 
</div> 

而在控制器中沒有真正改變。這是假設你沒有初始化$ scope.stops

DataFactory.getAllStops().then(function successCallback(res) { 
    console.log(res); 
    $scope.stops = res.data; 
}, function errorCallback(err) { 
    console.log("error: "); 
    console.log(err); 
    // TODO: Gracefully degrade 
}); 

另一種選擇是做上面同時顯示,而$ scope.stops是不確定的加載狀態。這與以上類似。