Return 在 Angular 中从工厂到控制器的连续数据

Return continuously data from Factory to Controller in Angular

我的工厂连接到蓝牙插件来读取数据。读取是连续完成的,直到我发送取消订阅命令。在工厂中,我可以看到正在连续读取数据,但数据并未发送回控制器。如何将数据发送回控制器?

我的工厂:

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。