2016-05-15 57 views
3
angular.module('demoapp').controller("EventControllerNearPosition", EventControllerNearPosition); 
EventControllerNearPosition.$inject = ["$scope", "ApiEventFactory", "ApiPositionFactory", "UserInteractionMessagesFactory", "$location"] 

function EventControllerNearPosition($scope, apiEvent, apiPosition, UIMfactory, $location){ 
UIMfactory.printUserSuccessMessages(); 
UIMfactory.printUserFailedMessage(); 

getAllPositions(); 

function getAllPositions() { 
    apiPosition.getAllPositions().then(function(data){ 
     $scope.positions = data.requested_positions; 
    }).error(function(error){ 
     UIMfactory.addUserFailedMessage("Something went wrong, try again!"); 
     $location.path("/"); 
    }); 
}; 

$scope.SearchEvent = function(){ 
    apiEvent.showNearbyEvents($scope.position_id).then(function(nearEvents){ 
     $scope.events = nearEvents; 
    }).error(function(error){ 
     UIMfactory.addUserFailedMessage("Something went wrong when fetching the events, try again!"); 
     $location.path("/"); 
    }); 
}; 
}; 

角碼^

<div class="event-container"> 
<div> 
    <h3>Ange position</h3> 
    <select id="position" data-ng-model="position_id"> 
     <option data-ng-repeat="position in positions" value="{{position.id}}"> 
      {{position.location_name}} 
     </option> 
    </select> 
</div> 
<div class="form-group"> 
    <input type="submit" class="btn btn-default" data-ng-click="SearchEvent()" value="Skicka"/> 
</div> 

的選擇將不綁定,我從我的API得到的位置。我調試了應用程序並檢查了我獲得了正確的值。我知道類似或「平等」的代碼在其他部分視圖中工作,所以我不明白爲什麼它在這裏不起作用。而且當我按下按鈕來觸發「SearchEvent」時,調試器中就沒有任何反應。我使用Firefox的,如果重要

感謝您的任何反饋!

回答

2

我只能看到一個錯誤,您應該從.then函數的響應對象中取data

function getAllPositions() { 
    apiPosition.getAllPositions().then(function(response){ 
     //change in below line 
     $scope.positions = response.data.requested_positions; 
    }, function(error){ 
     UIMfactory.addUserFailedMessage("Something went wrong, try again!"); 
     $location.path("/"); 
    }); 
}; 
+0

響應中沒有「數據」。它被稱爲response.requested_position。 Requested_positions是一個包含位置對象的數組 –

0

我可以很好地判斷,如果我能看到你得到的數據作爲迴應。但就這個代碼片段而言,.then()使用不當。 .then方法作爲.then(RESPONSE FUNCTION, ERROR FUNCTION) .error()不需要使用。

function getAllPositions() { 
    apiPosition.getAllPositions().then(function(response){ 
     $scope.positions = response.data.requested_positions; 
    },function(error){ 
     UIMfactory.addUserFailedMessage("Something went wrong, try again!"); 
     $location.path("/"); 
    }); 
}; 
+0

抱歉沒有工作 –

+0

我得到的「response」變量包含一個「requested_position」變量對象數組。它被稱爲response.requested_position。 –

+0

根據慣例,您的控制器將調用工廠方法。工廠方法將生成$ http請求。這將在.then()中以$ q作爲承諾等待響應。如果請求得到響應,它將執行$ q.resolve(),否則它將執行$ q.reject。在這裏,如果你想訪問你從工廠收到的控制器數據,它總會有一個'data'元素,你可以在其中找到你收到的數據,其他變量將保存與你的數據沒有直接關係的信息輸出。 –

0

我已經解決了我的問題。首先,我在response.requested_position(s)中刪除了「s」;

然後,我用answear Pankaj Parkar submited。除了我沒有在response.data.requested_positions中使用「數據」,因爲我使用「$ resource」而不是「$ http」或任何它被稱爲!

感謝您的所有反饋!