我的工厂连接到蓝牙插件以读取数据。 读取将连续进行,直到我发送取消订阅命令为止。 在工厂中,我可以看到正在连续读取数据,但是没有将数据发送回控制器。 如何将数据发送回控制器?
我的工厂:
angular.module('startup.services', []).factory('bluetoothFactory', ['$q', '$window', function($q, $window) {
...
return {
subscribe: function (delimiter) {
var q = $q.defer();
$window.bluetoothSerial.subscribe(delimiter, function (data) {
q.notify(data);
return data;
}, function (error) {
q.reject(error);
});
return q.promise;
}
....
我的控制器:
angular.module('startup.controllers',[]).controller('bluetoothCtrl', function($scope, $ionicModal, $timeout, bluetoothFactory)
{
.....
$scope.readInventory = function(zone)
{
bluetoothFactory.subscribe('\n').then(function(data)
{
$scope.info = data;
},
function(data)
{
// callback
console.log(data);
},
function(error)
{
$scope.error = error;
});
};
您有几种选择。 您可以将其作用域的实例传递给工厂,并使其在工厂内更新作用域,或者在这种情况下,我建议在工厂中使用$ broadcast并在控制器中使用$ watch。