2015-01-03 72 views
0

使用下面的代碼我不能將對象返回到工廠的返回值,並隨後在html中帶有空白字段,並帶有角度錯誤。Angular:將控制器更改爲工廠

Provider'theService'必須從$ get factory方法返回一個值。

我正在使用TingoDB(一個javascript版本的Mongo)和Angular在Node-Webkit中進行數據綁定的單頁應用程序。

我可以從控制器中查詢數據庫以顯示,過濾網頁等數據,但希望將此代碼更改爲Angular工廠,以便我可以跨多個控制器進行同步。 雖然我能夠使用僞數據將數據從工廠返回給控制器,但我一直無法從數據庫返回「實時」數據。

下面的代碼工作作爲控制器:

app.controller('MyCtrl', ['$scope', function($scope) { 
function getData(callback) { 
    collection.find({}).toArray(function(err, docs) { 
      $scope.$apply(function() { 
      callback(docs); 
      }); 
     }); 
} 

function info(b) { 
    // console.log(b); 
    $scope.items = b; 
} 

getData(info); 

}]); 

此更改爲出廠時不工作:

app.factory("theService", function($scope) { 
    function getData(callback) { 
     collection.find({})).toArray(function(err, docs) { 
       $scope.$apply(function() { 
       callback(docs); 
       }); 
      }); 
    } 

    function info(b) { 
     // console.log(b); 
     $scope.users = b; 

     return { 
      all: $scope.users, 
      first: $scope.users[0] 
     } 
    } 
    getData(info); 
}); 

控制器:

app.controller("MyCtrl", function($scope, theService) { 
    $scope.users = theService.all(); 
}); 
+1

你需要多一點的描述不是「不工作」 – Claies

+0

工廠必須返回的東西 – pixelbits

+0

@ user3801428你可以請創建plunk或小提琴,有很多未知的變量,使代碼看起來很雜亂 –

回答

0

這裏控制器,不知道你在哪裏定義變量collection,但最好將值傳遞給工廠

app.controller('MyCtrl', ['$scope','getData', function ($scope, getData) { 
    $scope.items = []; 

    getData(collection).then(function(items) { // pass "collection" to the factory 
     $scope.items = items; 
    }); 
}]); 

這是更好地利用工廠作爲global功能(或類的構造函數

app.factory('getData', ['$q', function ($q) { // you can't inject $scope to the factory   
    return function getData(collection) { 
     var defer = $q.defer(); // let's make it work more in angular way, use promises 

     collection.find({}).toArray(function (err, docs) { 
      if (err) { // fixme - don't really know how to handle exception here 
       defer.reject(err); 
      } else { 
       defer.resolve(docs); 
      }    
     }); 

     return defer.promise;     
    }; 
}]);