0

I'm trying to watch an array in a service and really struggling.

The Service

angular.module('starter.entities',[]).service('Entities', function() {
var _entities = this;

// public API
 this.locations = [];

 document.body.addEventListener("dbready", function(){
  buildModel(function(locations) {
    _entities.locations = locations;
   });
 });

The Controller

  .controller('DashCtrl', function($scope, Entities) {

    $scope.$watch(function() { return Entities.locations }, function() {
     doSomething...
   }, true);

.....

Bascially it's loading data in a database and I want to update the UI when the data is loaded.

The watch function is called when the first loading happens, but not when the data load happens.

Is there an easy way to get the $watch happening?

1 Answer 1

1

Events that come from outside the AngularJS framework need to notify the framework of changes to the model with $apply.

app.service('Entities', function($document, $rootScope) {
    var self = this;

    // public API
    this.locations = [];

    $document.find("body").on("dbready", function(){
      buildModel(function(locations) {
        self.locations = locations;
        //Use $apply to notify AngularJS framework
        $rootScope.$apply();
    });

});

For more information, see AngularJS $rootScope.scope API Reference -- $apply.

Sign up to request clarification or add additional context in comments.

Comments

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.