angular.js - 如何用angularjs讀取本地json?
黄舟
黄舟 2017-05-15 16:51:24
0
5
717

我讀取了text.json,並且賦值到$scope.data裡了,在html中用ng-repeat沒有反應。請問怎麼樣才能讓讀取出來的資料分別寫到html頁對應的位置去?
ps:這段程式碼運行時報錯說,找不到json檔案的路徑404.
js:

 function dataController($http,$scope) {
 $http.get("json/text.json").success(function(freetrial) { alert(freetrial);$scope.data = freetrial;});

json裡的數據:

{"freetrial":[{
"id": "01",
"imgurl": "images/1.jpg",
"status": "0"
},
{
"id": "02",
"imgurl": "images/2.jpg",
"status": "1"
}
]}

html:

<p ng-controller="dataController" ng-repeat="x in data|filter:{status:'0'}">
<p id="{{x.id}}">
<img ng-src="{{x.imgurl}}" />
</p>
</p>
黄舟
黄舟

人生最曼妙的风景,竟是内心的淡定与从容!

全部回覆(5)
仅有的幸福

既然已經提示404了,也就是沒找到json咯,應該是路徑錯誤

還有你的success()方法里面的freetrial實際上代表的是json的所有數據,所以你後面要取那個數組的時候這樣是取不到的。

應該這樣取:

 function dataController($http,$scope) {
     $http.get("json/text.json").success(function(data) {
         $scope.data = data.freetrial;
     });
 }
Ty80

你可以先配絕對路徑,如果成功說明沒其他問題的時候,再換相對路徑。

给我你的怀抱

你可以先配絕對路徑,如果成功說明沒其他問題的時候,再換相對路徑。

淡淡烟草味

問下你取出來了嗎?
我一直取不出來

曾经蜡笔没有小新

如果是404錯誤的, 就是get的json數據沒有獲取到, 也就是json的路徑出現了問題, 你的代碼我拷貝試了一下, 發現路徑對的前提下, 數據也不會顯示在頁面上.
但是:

function dataController($http,$scope) {
$http.get("json/text.json").success(function(freetrial) {   
        alert(freetrial);
        $scope.data = freetrial;
        console.log($scope.data);//可以打印出数据
    });
};

正確的get方法應該:

function dataController($http, $scope) {
    $http.get("rightUrl").success(function(data) {
        $scope.data = data.freetrial;
    });
};

data的作用:參考angular.js原始碼

 $http.get('test_data.json', 
     {cache: $templateCache}).success(function(userComments){
       self.userComments = userComments;
 });
熱門教學
更多>
最新下載
更多>
網站特效
網站源碼
網站素材
前端模板
關於我們 免責聲明 Sitemap
PHP中文網:公益線上PHP培訓,幫助PHP學習者快速成長!