我有一个控制器和工厂来处理列表。控制器需要获取工厂加载的列表并将其显示在视图中。我不能在工厂中使用getLists()方法,因为这需要从FireBase异步加载。这是我的控制器代码 -
angular.module('myApp.controllers', []).
controller('ListCtrl', ["$scope","listFactory", function($scope, ListFactory) {
$scope.lists = [];
$scope.$on("list_update", function(snapshot)
{
console.log(snapshot);
});
}]).
controller("EditListCtrl", ["$scope","listFactory", function($scope, ListFactory)
{
$scope.name = "";
$scope.items = [];
$scope.itemCount = 10;
$scope.save = function()
{
var List = {"items":[]};
for(var i = 0; i < $scope.itemCount; i++)
{
var item = $scope.items[i];
if(item != null)
{
List.items.push(item);
}
else
{
alert("Please fill all items of the list.");
return false;
}
ListFactory.putList(List);
$scope.items = [];
$scope.name = "";
}
}
}]);
listFactory看起来像这样 -
angular.module("myApp.factories", [])
.factory("listFactory", [function()
{
var lists = [{"name":"test"}];
var ListRef = new Firebase("https://listapp.firebaseio.com/");
var factory = {};
factory.getLists = function()
{
// this won't work
}
factory.putList = function(List)
{
ListRef.child("lists").push(List);
}
ListRef.on("child_added", function(snapshot)
{
// How do I get this back to the controller???
});
return factory;
}]);
ListRef将调度“child_added”事件,其中snapshot参数具有列表数据。我需要以某种方式将其恢复到控制器。我想用事件来做这件事,但我不确定如何在工厂和控制器之间做到这一点。我不想使用根范围,因为我认为这是不好的做法。
我是新手 - 任何帮助都会受到赞赏!
答案 0 :(得分:1)
首先更新列表变量以获得容器对象:
var lists = { items: [{ name: 'test' }] };
然后通过工厂公开对列表的访问,例如:
factory.getLists = function() {
return lists;
}
然后在控制器中设置范围var:
$scope.lists = ListFactory.getLists();
然后,每当触发child_added
事件时,请更新lists.items,控制器中的$scope
应反映更改。