【发布时间】:2014-08-24 05:55:39
【问题描述】:
我正在尝试使用 AngularJS 构建一个 Chrome 应用程序,我需要的一项功能是通过 chrome.system.network.getNetworkInterfaces 监视可用的网络接口。目前,我正在尝试将这些数据存储在工厂中并将其注入视图控制器:
(尽量减少)
工厂:
exampleApp.factory('exampleFactory', ['$http', function ($http) {
var service = {};
service.network_interfaces = 'Detecting network connections...';
chrome.system.network.getNetworkInterfaces(function(interfaces){
service.network_interfaces = interfaces;
})
// This outputs the expected array containing interface data
// in service.network_interfaces
console.log(service)
return service;
}]);
控制器:
exampleApp.controller('MainCtrl', ['$scope', '$http', 'exampleFactory', function($scope, $http, exampleFactory) {
// This outputs the expected array in network_interfaces, identical
// to the console output within the factory
console.log(exampleFactory)
// But then this outputs the initial 'Detecting network connections...'
// string set in the factory
console.log(exampleFactory.network_interfaces)
// And {{network_interfaces}} and {{factory_state}} in the view keep
// 'Detecting network connections...' as the value for network_interfaces
// permanently
$scope.factory_state = exampleFactory;
$scope.network_interfaces = exampleFactory.network_interfaces;
}]);
所以:
- 工厂似乎返回了一个好的
service对象,但我不确定为什么exampleFactory和exampleFactory.network_interfaces在控制器和工厂之间会有不同的状态,尤其是在控制器内部(无论他们被调用的顺序如何)。 - 我已经尝试了很多不同的解决方案,假设这是一个异步问题,但我认为
getNetworkInterfaces方法不会有明显的延迟,如果有的话,一切都为 Angular 正确设置返回数据后更新{{network_interfaces}}和{{factory_state}}视图绑定。 - 我还尝试在工厂中使用
$rootScope.$apply包装各种功能,作为在黑暗中拍摄,但结果与上述相同。
我已经搜索了很多东西,以发现我显然错过的任何概念,但我认为我忽略了一些基本的东西。如何将 getNetworkInterfaces() 数据以有用的状态输入到我的控制器中?
【问题讨论】:
标签: javascript angularjs dependency-injection google-chrome-app