$ scope变量与两个$ http.get请求不对齐

时间:2014-08-18 15:35:22

标签: angularjs

我有以下设置:

<div class="row" ng-repeat="hlos in hloss">
    <label for="entry_hlo_{[{ $index }]}" class="control-label"><span ng-if="$first">HLOS's</span></label>
    <button class="entry_remove_button">Remove</button>
    <select id="entry_hlo_{[{ $index }]}" class="hlos" name="hlos_{[{ $index }]}" ng-model="hlos_models[$index]" ng-options="hlosa for hlosa in hlos track by hlosa"></select>
</div>

(请原谅可怕的变量名,我正在使用语言atm)。

backendApp.controller('FeatureController', function ($scope, $http) {
    // ...
    $http.get('/features/1/').success(function(data) {
        $scope.hlos_models = {};
        $scope.hlos_models[0] = data['hlos']; // When the [0] assign is here, it does not work
    });
    // ...
    $http.get('/hloss/').success(function(data) {
        // Just some dummy data
        $scope.hloss[["MN","LA"], ["MN","AU"];
        $scope.hlos_models[0] = "MN"; // When the [0] assign is here it works 
    }

我在JS评论中有两个部分。为什么当我预先指定ng-model(所选字段)时,它不能正确生成而是放入?选项字段。当我将语句向下移动虽然看起来有效......我会想象所有这些JS都是在模板的其余部分实际呈现之前设置并生成的(我的js文件在<head>中)。

1 个答案:

答案 0 :(得分:1)

我不完全确定你的模特做了什么,但试试这个:

backendApp.controller('FeatureController', function ($scope, $http) {
// ...

// Just some dummy data
$scope.hloss[["MN","LA"], ["MN","AU"];
$scope.hlos_models = []; // initialize, now you have the object, so you can add to it.

$http.get('/features/1/').success(function(data) {
    $scope.hlos_models.push(data['hlos']); // push data when you get it
});
// ...
$http.get('/hloss/').success(function(data) {
     $scope.hlos_models.push("MN"); // push data when you get it
}

说明:您希望在收到数据时分配数据,因为某些调用可能需要比其他调用更长的时间并且是异步的...因此可能以不同的顺序到达。

<div class="row" ng-repeat="(key, hlos) in hloss">
<label for="entry_hlo_{[{ $index }]}" class="control-label"><span ng-if="$first">HLOS's</span></label>
<button class="entry_remove_button">Remove</button>
<select id="entry_hlo_{[{ $index }]}" class="hlos" name="hlos_{[{ $index }]}" ng-model="hlos_models[key]" ng-options="hlosa for hlosa in hlos track by hlosa"></select>