2017-07-03 108 views
0

我有一個工廠,從JSON文件加載數據的NG-重複,但是當我使用NG-重複它不能正常工作無法調用JSON文件到廠角

有我廠

quizApp.factory("DataService", dataService); 
function dataService($http) { 
var dataObj = { 
    mainInfo: null, 
    getList: getList() 
} 

function getList() { 
$http.get('data/list.json').then(function (myData) { 
    return myData.data.listInfo; 

}); 
} 
    return dataObj; 
} 

和控制器

quizApp.controller('listCtrl',function(DataService,$scope,$http){ 
    $scope.listInfo = dataService.getList; 

    $scope.changeActiveInfo =function(index){ 
     $scope.activeInfo = index; 
    } 
    $scope.activateQuiz = function(){ 
    QuizMetrics.changState("quiz", true); 
    } 
}); 

我的JSON文件

{ 
    "listInfo": [{ 
     "type": "Green Turtle", 
     "image_url": "http://www.what-do-turtles-eat.com/wp- 
     content/uploads/2014/10/Sea-Turtles-Habitat.jpg", 
     "locations": "Tropical and subtropical oceans worldwide", 
     "size": "Up to 1.5m and up to 300kg", 
     "lifespan": "Over 80 years", 
     "diet": "Herbivore", 
     "description": "The green turtle is a large, weighty sea turtle with a wide, smooth carapace, or shell. It inhabits tropical and subtropical coastal waters around the world and has been observed clambering onto land to sunbathe. It is named not for the color of its shell, which is normally brown or olive depending on its habitat, but for the greenish color of its skin. There are two types of green turtles—scientists are currently debating whether they are subspecies or separate species—including the Atlantic green turtle, normally found off the shores of Europe and North America, and the Eastern Pacific green turtle, which has been found in coastal waters from Alaska to Chile." 
}, 
{ 
    "type": "Loggerhead Turtle", 
    "image_url": "http://i.telegraph.co.uk/multimedia/archive/02651/loggerheadTurtle_2651448b.jpg", 
    "locations": "Tropical and subtropical oceans worldwide", 
    "size": "90cm, 115kg", 
    "lifespan": "More than 50 years", 
    "diet": "Carnivore", 
    "description": "Loggerhead turtles are the most abundant of all the marine turtle species in U.S. waters. But persistent population declines due to pollution, shrimp trawling, and development in their nesting areas, among other factors, have kept this wide-ranging seagoer on the threatened species list since 1978. Their enormous range encompasses all but the most frigid waters of the world's oceans. They seem to prefer coastal habitats, but often frequent inland water bodies and will travel hundreds of miles out to sea." 
} 

和當我使用ng-repeat="list in listInfo"它不起作用

+0

'then()'函數將被異步調用。因此它的return語句將被忽略。您將不得不將數據分配給數據對象,而不是將其返回。 – Adwaenyth

+0

首先檢查'dataService.getList'是否返回一些東西。 –

回答

1

你不是從getList函數返回任何東西。理想情況下,它應該爲您的情況返回promise

getList() { 
    return $http.get('data/list.json').then(function (myData) { 
    return myData.data.listInfo; 
    }); 
} 

然後訪問數據調用.then超過getList方法。

dataService.getList().then(function(list){ 
    $scope.listInfo = list; 
});