在angularjs app中加载初始数据

bom*_*sen 12 javascript jquery angularjs

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

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

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

app.js

var app = angular.module('feedbackApp', []);
Run Code Online (Sandbox Code Playgroud)

feedbackService.js

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

feedbackController.js

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

function init() {
    $scope.feedbackItems = feedbackService.getFeedbackPaged(1234, 1, 20);
}
});
Run Code Online (Sandbox Code Playgroud)

标记

<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>
Run Code Online (Sandbox Code Playgroud)

但是当我运行应用程序时,表是空的.我认为这是因为应用程序在服务中的数据添加到viewmodel($ scope)之前启动,但我不知道如何在应用程序启动之前初始化它,因此显示前20个表行.

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

提前致谢!

Aja*_*wal 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;});
}
});
Run Code Online (Sandbox Code Playgroud)

  • Ajay,你先生让我彻夜不停地拔头发!它就像一个魅力.非常感谢!!:-) (2认同)