user5839 user5839 - 2 months ago 10x
AngularJS Question

Angular watch array in service

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() {
}, 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?


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


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