2016-08-25 34 views
0

我有角度服务使用db,指令使用此服务的方法并查看我需要显示从db获得的值的位置。我坚持在需要绑定值来查看的时刻,首先我试图用控制器(service-> controller-> view)来实现,但我无法将视图绑定到控制器,并意识到对于异步分配值我需要指令和它的链接功能,我将元素移动到指令并试图从那里做,但仍然没有运气。所以,我有两个问题:ng-bind由promise解析返回的值

是我实现这种“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

只需重写你的链接功能如下:

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); 
     }); 
    }, 
+0

哇,你只是一个精灵,我已经失去了,因为它这么多的时间,非常感谢你 – kemsbe

+0

顺便说一下,为什么'回报'分配不起作用? – kemsbe

+0

我从来没有想过这个问题在那里 – kemsbe