Reputation: 3750
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?
Upvotes: 0
Views: 60
Reputation: 48948
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.
Upvotes: 1