2

I have an object in a service which is loaded asynchronously from a PouchDB.

I cannot in any way get the view to update as the service object is updated. I have followed many tutorials, answers, plnkrs, gists and just can't get it.

See http://plnkr.co/edit/jtFNs5FbrDBLlyZ5TATn?p=preview for my example. Any ideas?

Controller code:

var hubApp = angular.module('hubApp', []);

hubApp.service('objService', function($q, $timeout) {
  var objects = [];
  this.getObjects = function() {
      var data = $q.defer();
      var foo = data.promise;
      $timeout(function() {
        data.resolve([{"name": "first"},{"name": "second"}]);
      }, 2);
      foo.then(function(objs){
        console.log(objs);
        angular.forEach(objs, function(obj) {
          objects.push(obj);
        })
        console.log(objects);
      });
  }
  this.getObjects();
});

hubApp.controller('ListCrtl', ['$scope', 'objService',  
  function ($scope, objService) {
    $scope.objects = objService.objects;
  }
]);

View code:

  <body ng-controller="ListCrtl">
    <p ng-repeat="item in objects">Hello {{item.name}}!</p>
  </body>

Thanks.

16
  • var objects is not same as this.object. Why cant you call getObjects and chain it through the promise. How will you make sure that by the time the controller is invoked the promise would have resolved. Commented Aug 19, 2014 at 15:11
  • No, that is me trying to figure things out. Using this.objects results in an error in the .push code, although the .push was again me trying to troubleshoot. Commented Aug 19, 2014 at 15:13
  • Here plnkr.co/edit/uZxQ5L?p=preview Commented Aug 19, 2014 at 15:15
  • Isn't the issue the service should return the promise and then the controller should handle the THEN. And when the THEN completes update the scoped collection (ie. $scope.objects). Commented Aug 19, 2014 at 15:19
  • 1
    Thanks PSL. That is what I do in my code. But, it always felt like it was a little bit like splitting getting the data into two parts. The service would do the actually fetching of the data, but the controller would handle the mapping. But, I suppose this is correct from a separation of concerns viewpoint. Commented Aug 19, 2014 at 15:24

0

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.