【问题标题】:Not showing data in HTML from Angular app不显示来自 Angular 应用程序的 HTML 数据
【发布时间】:2016-10-28 11:24:12
【问题描述】:

我正在使用带有 Angular JS 应用程序的 Django REST API。我想在 HTML 表格中打印教室列表。这是我从 REST API 获得的 Json 数据:http://pastebin.com/raw/s0knYX89

这是 HTML

<div ng-app="userListApp">
    <div ng-controller="UsersController">
        <table class="table table-striped">
            <thead>
                <tr>
                    <th>Classroom</th>
                    <th>School</th>
                    <th>Academic year</th>
                </tr>
          </thead>
          <tbody>
              <tr ng-repeat="classroom in classrooms">
                  <td>{{classroom.classroom}}</td>
                  <td>{{classroom.school.school_name}}</td>
                  <td>{{classroom.academic_year}}</td>
              </tr>
          </tbody>
        </table>
    </div>
</div>

这里是 app.js

var userListApp = angular.module('userListApp', ['ngResource']);

userListApp.factory('Classroom', function($resource) {
      return $resource('/classrooms/?format=json', {}, {
          query: {
              method: 'GET',
              isArray:true,
            }
        });
    });


userListApp.controller('UsersController', function($scope, $resource, Classroom) {
  Classroom.query({},function(data) {
      $scope.classrooms = data;
      console.log(data);
        });
    });

不管怎样,我得到的就是这个

我输入console.log(data); 来检查数据是否到达页面,这就是我得到的结果:控制台中的所有数据,而 HTML 页面中没有 - 即使表格的行是三行,确切地说我应该得到的数字,但它们都是空白的。

有什么想法吗?

【问题讨论】:

  • 而不是尝试立即打印。使用 Promise 的 then 方法为异步任务定义回调,例如咨询服务

标签: angularjs django-rest-framework


【解决方案1】:

尝试在table 上添加ng-show

<table ng-show = "classrooms != null" class="table table-striped">
            <thead>
                <tr>
                    <th>Classroom</th>
                    <th>School</th>
                    <th>Academic year</th>
                </tr>
          </thead>
          <tbody>
              <tr ng-repeat="classroom in classrooms">
                  <td>{{classroom.classroom}}</td>
                  <td>{{classroom.school.school_name}}</td>
                  <td>{{classroom.academic_year}}</td>
              </tr>
          </tbody>
        </table>

你在哪里call 一个functnio 开始$http 请求?

【讨论】:

  • 谢谢,但它不适用于 ng-show。你的问题是什么意思?无论如何,我使用的是“$resource”,而不是“$http”。
  • 在你的控制器中你需要启动Classroom.query,你是怎么做的?
  • 嗯,我在原始问题中复制粘贴的脚本就是我所拥有的一切(我不知道这是否回答了你的问题,我是 Angular JS 的新手,我正在尝试理解一些概念!)
  • “$resource”网址可能是问题所在吗?就像我一样写,最后加上“?format=json”?
【解决方案2】:

正如您在console.log 中看到的,返回的数据是一个承诺。尝试正确访问api 响应。

【讨论】:

  • 我在 Angular 文档中找到了这个 Note: In contrast to $http.config, promises are not supported in $resource, because the same value would be used for multiple requests. If you are looking for a way to cancel requests, you should use the cancellable option.。那我该怎么办?
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2016-09-04
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多