2016-08-25 40 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