首頁  >  問答  >  主體

angular.js - 如何用angularjs讀取本地json?

我讀取了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>
黄舟黄舟2713 天前724

全部回覆(5)我來回復

  • 仅有的幸福

    仅有的幸福2017-05-15 16:53:24

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

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

    應該這樣取:

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

    回覆
    0
  • PHP中文网

    PHP中文网2017-05-15 16:53:24

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

    回覆
    0
  • 给我你的怀抱

    给我你的怀抱2017-05-15 16:53:24

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

    回覆
    0
  • 淡淡烟草味

    淡淡烟草味2017-05-15 16:53:24

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

    回覆
    0
  • 曾经蜡笔没有小新

    曾经蜡笔没有小新2017-05-15 16:53:24

    如果是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;
     });
    

    回覆
    0
  • 取消回覆