MongoDB中的数据在指令调用后加载

时间:2015-11-27 05:09:21

标签: javascript angularjs node.js mongodb express

我有一个小发票演示应用程序,我正在使用Angular构建。数据存储在MongoDB中,并在控制器名称中适当调用invoiceCtrl。控制器如下所示:

invCon.controller( 'invoiceCtrl', ['$http', function($http) {
        //Ajax call to retrieve items from db
        this.items = $http({
            method: 'GET',
            url: '/author'
        }).then(function successCallback(response){
            console.log('Succesful Response');
            return response.data[0].items;
        }, function errorCallback(response){
            console.log('Error Response');
            console.log(response);
        });

我遇到的问题是,当ajax请求检索此数据完成时,视图已经呈现模型并且没有加载任何内容,也就是说调用该指令并显示模板因为数据甚至存在。我认为双向数据绑定的工作方式是,当模型更新时,视图将是?我是否错过了Angular的双向数据绑定方式?

我发现的一些帖子似乎建议使用工厂来检索这些数据?这是我应该研究的东西吗?我对角度很新,所以任何帮助都会受到赞赏。

编辑1:

以下是指令:

(function(){

    var invDir = angular.module('invoice-directives', []);

    invDir.directive('envoyInvoice', function() {
        return {
            restrict: 'E',
            templateUrl: 'templates/invoice/invoice.html'
        };
    });

    invDir.directive('invoiceLogo', function(){
        return {
            templateUrl: 'templates/invoice/parts/invoice-logo.html'
        };
    });

    invDir.directive('invoiceMeta', function(){
        return {
            templateUrl: 'templates/invoice/parts/invoice-meta.html'
        };
    });

    invDir.directive('invoiceJob', function(){
        return {
            templateUrl: 'templates/invoice/parts/invoice-job.html'
        };
    });

    invDir.directive('invoiceTable', function(){
        return {
            templateUrl: 'templates/invoice/parts/invoice-table.html'
        };
    });

    invDir.directive('invoiceSummary', function(){
        return {
            templateUrl: 'templates/invoice/parts/invoice-summary.html'
        };
    });


})();

1 个答案:

答案 0 :(得分:1)

您不应该在成功处理程序中返回数据。而是将其存储在范围变量中。为此,首先将$scope注入您的控制器。

invCon.controller( 'invoiceCtrl', ['$scope', '$http', function($scope, $http) {
        //Ajax call to retrieve items from db
        $http({
            method: 'GET',
            url: '/author'
        }).then(function successCallback(response){
            console.log('Succesful Response');
            $scope.items = response.data[0].items;
        }, function errorCallback(response){
            console.log('Error Response');
            console.log(response);
        });

现在,您可以在视图html中使用items。由于angular支持双向绑定,因此只要$scope.items更新,视图就会自动更新。