来自控制器的数据未显示使用ng-repeat和factory

时间:2017-12-11 02:07:51

标签: angularjs

我试图使用ng-repeat将数据显示在表格中。 我有一个像这样编码的工厂:

Terminating app due to uncaught exception 'RLMException', reason: 'Realm accessed from incorrect thread.'

我的主模块编码如此

/// <reference path="../angular.js" />

var studentService = angular.module('StudentService', []);

studentService.factory('studentApi', function ($http) {
    var urlBase = "http://localhost:60892/api";

    var student = {};

    student.getStudents = function() {
        return $http.get(urlBase + '/Students');
    }

    return student;
})

在检查中,我可以看到我从网络API获得回复。

/// <reference path="../angular.js" />

var app = angular.module('MyApp', ['ngRoute', 'StudentService']);

//app.config(['$locationProvider', function ($locationProvider) {
//    $locationProvider.hashPrefix('');
//}]);

app.config([
    '$routeProvider',
    function($routeProvider) {
        $routeProvider
            .when('/Add', {
                templateUrl: 'templates/add.html',
                controller: 'AddController'
            })
            .when('/Edit', {
                templateUrl: 'templates/edit.html',
                controller: 'EditController'
            })
            .when('/Delete', {
                templateUrl: 'templates/delete.html',
                controller: 'DeleteController'
            })
            .when('/Home', {
                templateUrl: 'templates/home.html',
                controller: 'HomeController'
            })
            .otherwise({
                redirectTo: '/Home'
            });
    }
]);

app.controller('AddController', function ($scope) {
    $scope.message = "In add view"
});

app.controller('DeleteController', function ($scope) {
    $scope.message = "In delete view"
});

app.controller('EditController', function ($scope) {
    $scope.message = "In edit view"
});

app.controller('HomeController', function ($scope, studentApi) {
    getStudents();
    function getStudents() {
        studentApi.getStudents().then(function (students) {
                debugger;
            $scope.students = students;
        },
        function(error) {
            $scope.status = "Unable to retirieve data from the database: " + error.message;
        })

    }
});

但是当我尝试在我的html表中打印它时,该表创建了6行,但它没有任何值。即使我使用inspect元素来查看Array(27) 0 : {Id: 1, FirstName: "Daryl", LastName: "Richards", Age: 32, Gender: "Female"} 1 : {Id: 2, FirstName: "Fuller", LastName: "Guzman", Age: 27, Gender: "Male"} 2 : {Id: 3, FirstName: "Levi", LastName: "Lamb", Age: 32, Gender: "Male"} 3 : {Id: 4, FirstName: "Jared", LastName: "Bradley", Age: 32, Gender: "Female"} . . . length : 27 __proto__ : Array(0) 值,也没有。下面是我的HTML代码。

<td>

1 个答案:

答案 0 :(得分:1)

您正在将从网络服务获取的response对象分配给$scope.students。由于此视图未获得更新。 response对象不是数组,因此不会迭代。响应对象包含data字段,该字段将保存来自服务器的数据。因此,您需要从响应对象中分配数据字段。

只需从控制器

中对getStudents()方法进行一处更改即可
$scope.students = students;

$scope.students = students.data;