【问题标题】:Angular Js ng-repeat can't getting output from json array using ajaxAngular Js ng-repeat无法使用ajax从json数组中获取输出
【发布时间】:2016-09-17 17:40:51
【问题描述】:

我正在使用具有 ajax 的 Angular Js,但使用 ng-repeat 无法从 json 数组获取输出。警报获取 [Object object]... 等等,但通过使用 $scope.names= response[0].id; ,获得“1” id 警报。我需要获取表中的所有数据。有什么方法可以获取表格中的所有数据,而且我没有在控制器中使用$http,因为它不能在移动浏览器中工作,但在桌面上工作,我不知道为什么?请帮忙!

JS

var app = angular.module('studentApp',[]);
app.controller('StudentCntrl', function($scope){

$.ajax({
    url : '/fetchAllData',
    type : 'GET',
    success : function(response){
        $scope.names=response;
        //alert($scope.names);(This is working)
          } 
     });
});

JSP

<div ng-app="studentApp" ng-controller="StudentCntrl">

      <div class="table-responsive">
        <table class="table table-striped">
          <thead>
            <tr>
              <th>ID</th>
              <th>NAME</th>
              <th>EMAIL</th>
            </tr>
          </thead>
          <tbody>
            <tr ng-repeat="x in names">
              <td>{{x.id}}</td>
              <td>{{x.name}}</td>
              <td>{{x.email}}</td>

            </tr>
          </tbody>
        </table>
      </div>

Json

[{"id":"1","name":"abdul","email":"a@gmail.com"},{"id":"2","name":"pratyush","email":"p@gmail.com"},{"id":"3","name":"ankit","email":"a@gmail.com"},{"id":"45","name":"kjhj","email":"kjhkj"},{"id":null,"name":null,"email":null},{"id":null,"name":null,"email":null},{"id":null,"name":null,"email":null},{"id":"trffs","name":null,"email":null},{"id":"afa","name":"sdgfdsg","email":"dsagdsg"},{"id":"12","name":"pppp","email":"hjk,gh"}]

【问题讨论】:

  • 不要使用jQuery,注入$http
  • 我先尝试过,但在移动浏览器中无法使用。
  • 您是否在浏览器控制台中看到任何错误?
  • 哪个角度版本,以及浏览器类型和版本?正如其他人所提到的,如果正确使用 $http,它应该可以在移动设备上运行。
  • 你有什么错误?

标签: javascript jquery angularjs json ajax


【解决方案1】:

当使用 $ajax 调用更新范围时(您应该使用 $http),您必须使用 $scope apply 来更新您的绑定。

$scope.$apply(function(){
    $scope.names = response.data;
});

【讨论】:

  • 你能举个例子解释一下吗?
  • 我为你构建了一个小例子,在 .done 函数中使用 jQuery 和 $scope.$apply。我更喜欢使用 .done 和 .fail ,因为它使用返回的 promise 对象。 codepen.io/robbert/pen/rrLQgq
  • 非常感谢,它可以在桌面和移动浏览器上运行..!! :-)
【解决方案2】:

使用 $http 代替 ajax 调用,如下所示

var app = angular.module('studentApp', []);
app.controller('StudentCntrl', function($scope,$http) {
    $http.get('data.json').then(function (response){
                  console.log(response.data.pages);
                $scope.names = response.data;
        });
});

这是工作 DEMO

【讨论】:

  • 我先试过了,它在移动浏览器中不起作用,spring config中存在一些问题,所以我正在尝试这种方法。
  • 如果您使用 Angular,这就是方式,它也应该适用于移动设备
  • 实际上我正在使用我的系统 ip 在移动浏览器上验证我的项目,这是它无法在移动设备上运行的原因吗?喜欢 198.0.X.X:8080/home
猜你喜欢
  • 1970-01-01
  • 2017-11-05
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多