我将Angular与Firebase一起使用,并且在尝试使工厂使用过滤器时遇到错误。
app.factory('itemsFactory', ["$scope", '$rootScope', "$firebase", "simpleLogin",
function($scope, $rootScope, $firebase, simpleLogin) {
var ref = new Firebase("https://------.firebaseio.com/");
var items = $scope.items
$scope.items = [];
var sync = $firebase(ref);
$scope.items = sync.$asArray();
$rootScope.auth = simpleLogin;
return items;
}]);
app.filter('orderObjectBy',['itemsFactory', function (itemsFactory) {
return function (items) {
var filtered = [];
for (var i = 0; i < items.length; i++) {
var item = items[i];
if (item.hot) {
filtered.push(item);
}
};
for (var i = 0; i < items.length; i++) {
var item = items[i];
if (!item.hot) {
filtered.push(item);
}
};
return filtered;
};
}]);
这是相关的HTML:
< tr ng-repeat="item in items | orderObjectBy:'hot' track by $index">
这是我在控制台中得到的:
ngRepeat:项目中的项目orderObjectBy:$ index的“热门”曲目 copeProvider%20%3C-%20%24scope%20%3C-%itemsFactory%20%3C-%orderObjectByFilter at Error(native)
似乎我搞砸了依赖注入。但是这样做的正确方法是什么?
答案 0 :(得分:1)
您可以利用AngularFire的可扩展性来排序列表而无需指令:
app.factory('HotList', function($firebase) {
function hotComparator(a,b) {
if( a.hot === b.hot ) {
// if both are hot or not, then sort by $id
return strcmp(a.$id, b.$id);
}
else {
// place hot items at the top
return a.hot? -1 : 1;
}
}
function strcmp(str1, str2) {
// http://phpjs.org/functions/strcmp/
return ((str1 == str2) ? 0 : ((str1 > str2) ? 1 : -1));
}
return function(ref) {
var list = $firebase(ref).$asArray();
function resort() {
list.sort(hotComparator);
}
list.$watch(resort);
resort();
return list;
};
});
app.controller('ctrl', function(HotList) {
// automagically sorted by hot/not and $id
$scope.list = HotList(new Firebase(URL));
});
要使您的指令正常工作,您需要复制数组并在副本上调用sort,这将更加简单。
app.filter('orderObjectBy', function($firebase) {
function hotComparator(a,b) {
if( a.hot === b.hot ) {
// if both are hot or not, then sort by $id
return strcmp(a.$id, b.$id);
}
else {
// place hot items at the top
return a.hot? -1 : 1;
}
}
function strcmp(str1, str2) {
// http://phpjs.org/functions/strcmp/
return ((str1 == str2) ? 0 : ((str1 > str2) ? 1 : -1));
}
return function(items) {
var list = items.slice();
list.sort(hotComparator);
return list;
};
});
你在视图中的用法不太对,所以试试这样:
ng-repeat="item in items track by $id | orderObjectBy:'hot'"