ng-bind到promise resolve返回的值

时间:2016-08-25 10:57:05

标签: javascript angularjs promise

我有角度服务使用db,使用此服务的方法指令,并查看我需要显示从db获取的值的位置。我坚持在需要绑定值来查看的那一刻,首先我尝试用控制器(service-> controller-> view)来做,但是我无法将值从视图绑定到控制器1并实现对于异步赋值我需要指令及其链接函数,我将元素移入指令并尝试从那里做,但仍然没有运气。所以,我有两个问题:

我的方式是实施这个" AngularJS方式"?

如果是的话,我怎样才能将这个值绑定到最后查看?

以下是代码(部分内容,为问题裁剪):

服务

var purchaseHistoryService = function ($q) {

    this.getUserPurchases = function() {
        var deferred = $q.defer();
        Parse.Cloud.run('getUserPurchases').then(function(res) {
            var purchases = [];

            // take only part we need from purchase objects
            if(res) {
                res.forEach(function (purchase) {
                    purchases.push(purchase.attributes);
                });
            }
            return deferred.resolve(purchases);
        }, function(err) {
            return deferred.reject(err);
        });
        return deferred.promise;
    };
};

module.exports = purchaseHistoryService;

指令:

var purchaseHistoryTable = function (purchaseHistoryService) {
    return {
        restrict: 'E',
        link: function (scope) {

            scope.purchases = purchaseHistoryService.getUserPurchases().then(function(res) {
                console.log(res); // gives expected result, array of objects
                return res;
            }, function(err) {
                console.error(err);
            });
        },
        templateUrl: "purchaseHistoryTable"
    };
};

module.exports = purchaseHistoryTable;

查看:

.table--purchase-history
.table_cell-content_header--purchase-history(ng-bind="purchases") // check binding here, got '[object Object]'
.table_row--purchase-history(ng-repeat="purchase in purchases")
    .table_cell--purchase-history-big
        .table_cell-content--bought-packs
            .table_cell-content_header--purchase-history(ng-bind="purchase.totalPrice")
        .ver-line--purchase-history

调查问题我发现如果我改变这样的指令:

var purchaseHistoryTable = function (purchaseHistoryService) {
    return {
        restrict: 'E',
        link: function (scope) {
            scope.purchases = 'example';
        },
        templateUrl: "purchaseHistoryTable"
    };
};

module.exports = purchaseHistoryTable;

我有例子'在我看来,这没关系,但当我添加分配给承诺解决价值时,即使将结果函数的返回值更改为[object Object]

,我也得到return 'example';

再次提问:

我的方式是实施这个" AngularJS方式"?

如果是,如何将此值绑定到最后查看?

1 个答案:

答案 0 :(得分:1)

只需重写您的链接功能:

link: function (scope) {
       purchaseHistoryService.getUserPurchases().then(function(res) {
            console.log(res); // gives expected result, array of objects
            scope.purchases = res;// <--- HERE COPY IN THE THEN
        }, function(err) {
            console.error(err);
        });
    },