Home  >  Q&A  >  body text

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 days ago730

reply all(5)I'll reply

  • 仅有的幸福

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

    Since it has prompted 404, which means not foundjson, it should be the wrong path

    And your success()方法里面的freetrial actually represents all the data of json, so when you want to get the array later, you won’t be able to get it this way.

    should be taken like this:

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

    reply
    0
  • PHP中文网

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

    You can configure the absolute path first, and then change to the relative path if it succeeds and there are no other problems.

    reply
    0
  • 给我你的怀抱

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

    You can configure the absolute path first, and then change to the relative path if it succeeds and there are no other problems.

    reply
    0
  • 淡淡烟草味

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

    Have you taken it out?
    I haven’t been able to take it out

    reply
    0
  • 曾经蜡笔没有小新

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

    If it is a 404 error, it means that the json data of get has not been obtained, that is, there is a problem with the json path. I copied your code and tried it. If the path is correct, the data will not be displayed on the page.
    But:

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

    The correct get method should be:

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

    The role of data: refer to angular.js source code

     $http.get('test_data.json', 
         {cache: $templateCache}).success(function(userComments){
           self.userComments = userComments;
     });
    

    reply
    0
  • Cancelreply