How to use angular ng-repeat with an Web api?

旧时模样 提交于 2021-02-08 07:59:24

问题


I'm trying to build a website using front-end html and get its data from a Web-api. My Web-api returns a json format. So I was trying to use the Get request using Angular $http and ng-repeat directive. My angular controller is like this -

'use strict';  app.controller('blogsController', ['$scope','$http', function ($scope, $http) {
$http.get('www.example.com/api/blog')
   .then(function(res){
      $scope.blogs = res.data;
    });
}]);

The html code looks like this -

<body app="ng-app" >
   <div ng-repeat="xr in blogs" >
     <div id="blog_title" >
       {{xr.blog_title}}
     </div>

     <div id="blog_text">
       {{xr.blog_text}}
     </div>
   </div>

</body>

I have tried this but this is not getting me the data from the blog web api.

Please help me to get the solution.....


回答1:


there is nothing wrong in your code

<div ng-repeat="xr in blogs" >
     <div id="blog_title" >
       {{xr.blog_title}}
     </div>

     <div id="blog_text">
       {{xr.blog_text}}
     </div>
   </div>

but make sure that your res.data must follow an arrangement like below:

res.data = [{'blog_title': 'title value1', 'blog_text':'text value'}
            {'blog_title': 'title value2', 'blog_text':'text value'}
            {'blog_title': 'title value3', 'blog_text':'text value'}]

print your res.data in web console using console.log to confirm.




回答2:


You are missing ng-controller on the template, and app should be ng-app

<body ng-app="ng-app" ng-controller="blogsController">
   <div ng-repeat="xr in blogs" >
     <div id="blog_title" >
       {{xr.blog_title}}
     </div>

     <div id="blog_text">
       {{xr.blog_text}}
     </div>
   </div>

</body>


来源:https://stackoverflow.com/questions/59926579/how-to-use-angular-ng-repeat-with-an-web-api

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!