12

我目前正在尝试开发一个 AngularJS 应用程序。这是我第一个使用 AngularJS 的应用程序,我想我很清楚它是如何工作的,因为我已经做了几年 Silverlight 开发人员 :-)

但是,我无法弄清楚一件简单的事情:如何在应用程序启动时获取其初始数据。

我需要的是一个简单的数据表,其中可以内联编辑一些字段(通过下拉菜单) 我的应用程序结构是这样的:

应用程序.js

var app = angular.module('feedbackApp', []);

反馈服务.js

app.service('feedbackService', function ($http) {
this.getFeedbackPaged = function (nodeId, pageNumber, take) {
    $http.get('myUrl', function (response) {
        return response;
    });
};
});

反馈控制器.js

app.controller('feedbackController', function ($scope, feedbackService, $filter) {
// Constructor for this controller
init();

function init() {
    $scope.feedbackItems = feedbackService.getFeedbackPaged(1234, 1, 20);
}
});

标记

<html ng-app="feedbackApp">
<head>
    <script src="http://code.jquery.com/jquery-1.10.1.min.js"></script> 
    <script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.0.7/angular.min.js"></script>
</head>
<body>
    <table class="table" style="border: 1px solid #000; width:50%;">
        <tr ng-repeat="fb in feedbackItems | orderBy: 'Id'" style="width:auto !important;">
            <td data-title="Ansvarlig">
                {{ fb.Name }}
            </td>
            <td data-title="Kommentar">
                {{ fb.Comment }}
            </td>
        </tr>
    </table>
</body>

但是当我运行应用程序时,表是空的。我认为这是因为应用程序在来自服务的数据添加到视图模型($scope)之前启动,但我不知道如何在应用程序启动之前对其进行初始化,因此显示了前 20 个表行。

有谁知道如何做到这一点?

提前致谢!

4

1 回答 1

19

您应该稍微修改一下代码以使其正常工作,因为您在这里使用的是 Promise,您应该使用 .then

app.service('feedbackService', function ($http) {
this.getFeedbackPaged = function (nodeId, pageNumber, take) {
    return $http.get('myUrl');
};
});

app.controller('feedbackController', function ($scope, feedbackService, $filter) {
// Constructor for this controller
init();

function init() {
   feedbackService.getFeedbackPaged(1234, 1, 20).then(function(data){$scope.feedbackItems=data;});
}
});
于 2013-09-11T18:08:04.993 回答