2017-09-13 85 views
0

不知道我在這裏設置錯了,只是在json中顯示書籍, 我認爲這可能是視圖或控制器可能是錯誤的,但我不確定。謝謝你的幫助。Angular不從外部json加載數據

<div class="book col" ng-repeat="book in myBooks"> 
    <h3 class="title">{{book.title}}</h3> 
    <p class="author">{{book.author}}</p> 
    </div> 

services.js

app.factory('books', ['$http', function($http) { 
    return $http.get('books.json') 
    .success(function(data) { 
     return data; 
    }) 
    .error(function(err) { 
     return err; 
    }); 
}]); 

books.json

{ 
    "per_page":20, 
    "page":1, 
    "total_pages":1468, 
    "total_results":29346, 
    "books":[ 
     { 
     "uuid":"235b68e4-5b16-4a25-b731-45c7e67c351e", 
     "id":98024, 
     "title":null, 
     "author":null, 
     "language":null, 
     "createtime":"2016-05-19T13:09:40.963+00:00" 
     }, 
     { 
     "uuid":"5e87daca-e87b-4324-a652-e06d5349bd82", 
     "id":98055, 
     "title":null, 
     "author":null, 
     "language":null, 
     "createtime":"2016-05-23T15:50:11.777+00:00" 
     } 

Controller.js

app.controller('BookshelfController', ['$scope', 'books', function($scope, books) { 
    books.success(function(data) { 
    $scope.myBooks = data; 
    }); 
}]); 
從你的工廠,包含你的函數對象

回答

2

返回,呼叫將返回你的$http.get()

app.factory('books', ['$http', function($http) { 
    return { 
     getBooks: function() { 
      return $http.get('books.json'); 
     } 
    }; 
}]); 

的結果,因爲$http.get返回一個無極的對象,在你的控制器使用then獲得從響應的結果。

app.controller('BookshelfController', ['$scope', 'books', function($scope, books) { 
    books.getBooks().then(function (data) { 
     $scope.myBooks = data; 
    }, function (err) { 
     console.log(err); 
    }); 
}]); 

另請檢查您的url是否正確。