2014-01-23 58 views
1

我有一个控制器和工厂来处理列表。控制器需要获取工厂加载的列表并将其显示在视图中。我不能在工厂中使用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”事件在快照的说法是有名单的数据。我需要以某种方式回到控制器。我想用事件做这件事,但我不知道如何在工厂和控制器之间做到这一点。我不想使用根范围,因为我认为这是不好的做法。

我是新来的 - 任何帮助将不胜感激!

回答

1

首先更新您的列表变量有一个容器对象:

var lists = { items: [{ name: 'test' }] }; 

然后通过工厂暴露访问列表,如:

factory.getLists = function() { 
    return lists; 
} 

然后设置在您的控制器范围VAR:

$scope.lists = ListFactory.getLists(); 

然后,无论何时触发child_added事件,更新列表s.items和来自控制器的$scope应该反映这些变化。

+1

令人神往的魔法... –

+0

我也建议你阅读下面的内容:http://jimhoskins.com/2012/12/14/nested-scopes-in-angularjs.html –

+0

好吧,它确实有点工作,但只有在我开始操纵视图。当页面加载时,它应该拉入2个列表,但只有当我开始在其中一个输入框中输入时才会这样做。任何想法为什么? –