2014-12-07 51 views
1

我一直在努力適當地實現這個,我以爲我有它,但基於這個例子,我做錯了。你如何在控制器中使用這個工廠?預期的結果是什麼?瞭解AngularFire擴展FirebaseArray示例?

的例子:

app.factory("ListWithTotal", ["$FirebaseArray", "$firebase", function($FirebaseArray, $firebase) { 
    // create a new factory based on $FirebaseArray 
    var TotalFactory = $FirebaseArray.$extendFactory({ 
    getTotal: function() { 
     var total = 0; 
     // the array data is located in this.$list 
     angular.forEach(this.$list, function(rec) { 
     total += rec.amount; 
     }); 
     return total; 
    } 
    }); 
    return function(listRef) { 
    // override the factory used by $firebase 
    **// why do listRef and ref not match here? 
    //where does listRef or ref come from** 
    var sync = $firebase(ref, {arrayFactory: TotalFactory}); 
    return sync.$asArray(); // this will be an instance of TotalFactory 
    } 
}]); 

我已經能夠使用一個版本擴展的工廠不包括引用到一個新的火力點的回報。例如:一個待辦事項清單保持計數:http://plnkr.co/edit/iAGvPHFWn2GSPGzBRpKh?p=preview

+0

這是一個錯字。它們都應該是'listRef'或'ref'。沒有一個和另一個。 – user2943490 2014-12-08 05:37:16

回答

1

這是一個錯字。他們應該都是listRefref。沒有一個和另一個。

由於ListWithTotal工廠返回一個功能,你使用它的控制器是這樣的:

.controller('MyController', function ($scope, $window, ListWithTotal) { 
    var ref = new $window.Firebase("//some-url/data"); 
    $scope.listWithTotal = ListWithTotal(ref); 
}); 
+0

酷,所以它取代了$ firebase功能。那裏需要$窗戶嗎?我通常只是寫var ref = new Firebase('/ path-to-firebase'); – EmptyPockets 2014-12-08 15:55:47

+1

由於'$ window'是Angular的窗口對象封裝,所以全局對象的任何屬性(如'Firebase')也可以在'$ window'中使用。讓您的代碼引用'$ window'可以讓您輕鬆地在測試中嘲笑全局範圍內的事情。 – user2943490 2014-12-08 22:19:49