在 angularjs 应用程序中加载初始数据

Load initial data in an angularjs app

本文关键字:数据 加载 angularjs 应用程序      更新时间:2023-09-26

我目前正在尝试开发一个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 个表行。

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

提前感谢!

你应该稍微修改一下你的代码以使其工作,因为你在这里使用 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;});
}
});