Search code examples
angularjsbluetoothcordova-plugins

Return continuously data from Factory to Controller in Angular


My factory connects to a bluetooth plugin to read data. The read is done continuously until I send a unsubscribe command. In the factory I can see that the data is being read continuously, however the data is not sent back to the controller. How can I send the data back to the controller?

My factory:

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;
    }
....

My controller:

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;
    });
  };

Solution

  • You have a couple of options available to you. You can either pass the factory an instance of your scope and have it update the scope within the factory or this is one case where I would advocate the use of $broadcast in the factory and $watch in the controller.