After saving a resource in angular.js, I want to broadcast the changes so a list view can be updated.
function EnvironmentCtrl($rootScope, $scope, $location, $routeParams, environmentService) {
environmentService.get($scope, $routeParams.id);
$scope.id = $routeParams.id
$scope.save = function(){
$scope.environment.$save(function(data) {
$rootScope.$broadcast("model-update");
});
}
}
function NavController($scope, $http, $routeParams, environmentService) {
environmentService.list($scope);
$scope.$on("model-update", function(){
environmentService.list(function(data){
$scope.environments = data;
console.log("update called", $scope.environments);
});
});
}
The communication between these controllers when EnvironmentCtrl.save is called works ok. The console.log gets called and the data returned to the callback by the service gets correctly set in the $scope.
The relevant part of my service looks like this:
services.factory('environmentService', [ '$resource', function($resource) {
var environmentService = {};
environmentService.list = function(callback) {
var url = "/service/environment/"
$resource(url).query(function(data) {
callback(data);
});
}
return environmentService;
} ]);
My view looks like:
<li data-ng-repeat="env in environments">
<a href="#/environment/{{env.id}}">{{env.name}}</a>
</li>
But doesn't get updated until a refresh.
This is all 'within angular' (as far as I see) and I would have thought that it would 'just work'. I've tried calling $digest from within the callback. $apply complains a digest is already in progress.
Can anyone tell me why the view does not get updated?
I agree that by the time the event arrives the model should have been updated. It looks like a bug in angular.
Till then you can emit the event inside a $timeout if that works for you.
$timeout(function() {$rootScope.$broadcast("model-update");}, 0);