我沒有正確地考慮angular的$ http.get工作,所以也許你可以幫我重新調整。我正在開發一個嚮導,其中每個步驟都是一個單獨的html文件,並且步驟序列位於JSON文件中。我想要做的是在JSON文件中讀取,然後:
- 創建一個步驟列表作爲指南。
- 通過ng-include顯示該步驟的內容。
- 創建指向上一步和下一步的按鈕。
從我在Service vs. Provider vs. Factory,AngularJS: factory $http.get JSON file閱讀,以及類似的話題,我可以創建一個服務或工廠的JSON閱讀。這樣做會創建一個promise對象,然後在數據到達時傳遞給該對象以進行填充。將數據插入到視圖中綁定的模型時可以找到它。如果我需要數據來計算下一步按鈕之類的東西,但我擁有的只是一個承諾對象 - 我無法建立指向上一步和下一步的鏈接並設置它們的狀態。在繼續執行代碼之前,有沒有辦法讓角度等待直到數據到達?這是想想它的正確方法嗎?
這裏是一個plunker和一些代碼片段:
JSON:
[{
"name" : "Step 1",
"id" : "step-1",
"src" : "step-1.html",
"state" : "active"
},
{
"name" : "Step 2",
"id" : "step-2",
"src" : "step-2.html",
"state" : "unavailable"
},
{
"name" : "Step 3",
"id" : "step-3",
"src" : "step-3.html",
"state" : "unavailable"
}]
廠:
workflow.factory('getWorkflow', function($http, $q) {
return {
getFlow: function() {
var deferred = $q.defer();
$http.get('steps.json').success(function(data) {
deferred.resolve(data);
}).error(function(){
deferred.reject();
});
return deferred.promise;
}
}
});
控制器摘錄:
var workflow = angular.module("workflow", ['getWorkflow']);
workflow.controller("showStep", function($scope) {
$scope.workFlow = {}; // Create the workFlow object
$scope.workFlow.steps = []; // Create an empty array to hold the steps
$scope.workFlow.steps = getWorkflow.getFlow();
... set the first step as the active step and point to the HTML file ...
$scope.workFlow.buildNavButtons = function() {
scope.workFlow.buttonArray = []; // Create/reset the array of buttons to nothing
// The button for the PREVIOUS step.
if ($scope.workFlow.activeStepIndex > 0) { // Only add button if not the first step
var prevButton = {};
prevButton["destination"] = $scope.workFlow.activeStepIndex - 1;
prevButton["buttonText"] = "<< " + $scope.workFlow.steps[$scope.workFlow.activeStepIndex - 1].name;
prevButton["buttonClass"] = "workflow-previous";
$scope.workFlow.buttonArray.push(prevButton);
}
...
HTML
<!-- PREVIOUS AND NEXT STEP BUTTONS -->
<div id="workflow_navigation">
<ul>
<li data-ng-repeat="button in workFlow.buttonArray">
<button class = "{{ button.buttonClass }}"
ng-click="workFlow.updateStep(button.destination)">
{{ button.buttonText }}
</button>
</li>
</ul>
</div>
這工作 - 謝謝!我不明白.then方法是如何工作的,現在它是有道理的。 (當我可以的時候將會+1。:) –