![](/img/trans.png)
[英]Not getting json data from json-angularjs call to an external url with $http.get
[英]AngularJS $http.get don`t get data from json file
我在控制器中有下一個代碼
app.controller('controller', function ($scope, $routeParams, $http) {
$http.get('db.json').success(function(data) {
$scope.phone = data;
});
});
這是 JSON 文件:
{
"title1" : "first title",
"title2" : "second title",
"title3" : "third title",
}
然后我嘗試像這樣打印數據:
<h1>{{ db.title1 }}</h1>
但在瀏覽器中我什么也沒看到。 我究竟做錯了什么?
我解決了第一個問題,但還有另一個問題
這是在 json 文件中
"nameArr" : [
{
"title": "title",
"image": "images/img.png"
},
{
"title": "title",
"image": "images/img1.png"
},
{
"title": "title",
"image": "images/img2.png"
},
{
"title": "title",
"image": "images/img3.png"
}
]
和 ng-repeat 在 html 中這樣
<div class="item" ng-repeat="items in nameArr">
<img ng-src="{{ items.image }}">
<h1>{{ items.title }}</h1>
</div>
再一次不要顯示任何東西
兩件事:1)您在模板中引用的對象應該立即聲明,而不是在回調中,2)返回的數據將是一個字符串,您需要使用angular.fromJson或 JSON.parse 來將其解析為一個對象。
$scope.phone = {};
app.controller('controller', function ($scope, $routeParams, $http) {
$http.get('db.json').success(function(data) {
$scope.phone = angular.fromJson(data);
});
此外,在您的模板中,您無法在 db 內部獲取此信息,因為您將其放在手機上:
<h1>{{ phone.title1 }}</h1>
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.