Angular.js API调用 – 我应该使用工厂吗?

我正在使用Trello API,Node.js(和Node-Trello软件包)和Angular.js( github repo )来开发Electron应用程序,

当用户授权他们的Trello应用程序时,我保存一些configuration文件数据; 其中一些是所有Trello板的ID列表。

我有一个控制器来处理显示他们的董事会名单。 在这个控制器中,我从数据库中提取板ID列表,并得到一个数组

["893482938480", "0938492830"] 

然后我调用一个函数,我传递了这个电路板ID的数组,像这样…

 // get data for boards $scope.get_board_data = function(boardIDArray) { for(var i = 0; i < boardIDs.length; i++){ t.get("/1/boards/" + boardIDs[i], function(err, data) { if (err) throw err; board_info = data; board_names.push(board_info['name']); $scope.board_names = board_names; //console.log($scope.board_names); return $scope.board_names }); } } $scope.board_array = $scope.get_board_data(boardIDs); 

问题是,如果我console.log $ scope.board_names函数的外面,那么我得到undefined 。 但如果我loginfunction,那么我得到所需的数据。 我有点卡在这里 任何帮助将不胜感激!

PS我也试过在$ scope.board_names上使用$watch ,但是我仍然undefined 。 这是我试过的…

 $scope.$watch('$scope.board_names', function(newValue, oldValue) { console.log('$scope.board_array: ' + newValue); }); 

编辑好了,看来这个代码确实有效; 我改变$scope.board_array = $scope.get_board_data(boardIDs);$scope.get_board_data(boardIDs); 然后当我点击一个菜单项时,视图最终会实现有数据供它使用。

新问题如何让视图在页面加载时获取这些数据?

这应该是一个工厂? 这是他们用来做什么的?

我会build议,而不是使用简单的工厂,而是使用资源 。 它们是专门为处理REST呼叫而专门创build的工厂。 请参阅下面的链接了解更多信息。

不仅是专门为此devise的资源,还允许您创build一个集中式系统,使您可以在需要时轻松添加更多REST调用。

厂:

 (function () { 'use strict'; angular .module('app') .factory('YourFactoryName', ['$http', function ($http) { //Add your other things you need to inject I don't know what your using. //Probably pass your t object, or if you can inject it here, if it is in fact a service of its own var factory = {}; factory.get_board_data = function (boardIDArray) { for(var i = 0; i < boardIDs.length; i++){ t.get("/1/boards/" + boardIDs[i], function(err, data) { if (err) throw err; board_info = data; board_names.push(board_info['name']); return board_names; }); }; }; return factory; }]); }()) 

$scope.board_array=YourFactoryName.get_board_data();调用它$scope.board_array=YourFactoryName.get_board_data();

如果您想要立即加载,您可以在控制器的开始处调用它。