I need to communicate state which several services need and originates in data bound to the scope of a controller. What would a good and \'Angular zen\' way to
I made a demo plunker :http://plnkr.co/edit/RihW4JFD8y65rDsoGNwb?p=preview
There are lots of different ways and this question is somehow very broad, but I wanted to share another approach.
Your problem starts with the way you communicate between controllers and services.
Instead of creating services as objects with methods (which enforce you to use the observer pattern) , you can point scopes directly to services by creating data objects services and let $digest
make the work for you.
The very reason why angular uses $scope is to let you use POJO rather than an observer pattern like other frameworks. When you create these kind of method driven services you introduce the same pattern that angular tries to avoid.
It's important to note that you must point to properties on the service object and not to the object reference itself.
app.factory('FooService', function($rootScope, Configuration){
$scope = $rootScope.$new();
$scope.Configuration = Configuration;
var foo = {
data : null
};
$scope.$watch('Configuration', function(config){
foo.data = // do something with config
}, true)
return foo;
});
app.factory('Configuration', function(){
return {
data : 'lol'
}
});
app.controller('SettingsCtrl', function($scope, Configuration){
$scope.config = Configuration;
});
app.controller("HomeCtrl",function($scope, FooService){
$scope.foo = FooService;
});
Actually, I prefer the use of $scope.$broadcast
mostly for performance reasons but also because it's the most elegant way to share states across differnet parts of the application. I really don't care about global states, I use namespaces for my events.