How can I switch out a service on-the-fly and have all components (relying on the service) automatically be bound to the data on the new strategy?
I have a Storage
service and two storage strategies, StorageStrategyA
and StorageStrategyB
. Storage
provides the public interface to controllers and other components to interact with:
angular.module('app').factory('Storage', function ($injector) {
var storage;
var setStrategy = function (name) {
storage = $injector.get(name);
};
setStrategy('StorageStrategyB');
return {
getItems: function () {
return storage.getItems();
}
// [...]
};
});
But when the strategy is changed, the two-way binding breaks and the view doesn't update with items from getItems()
from the new strategy.
I've created a Plunker to illustrate the problem.
Is there a way to combine the strategy pattern with AngularJS and keep the two-way binding?
Please note that in my actual app I cannot just call Storage.getItems()
again after the strategy has been changed, because there are multiple components (views, controllers, scopes) relying on Storage
and the service change happens automatically.
Edit:
I have forked the Plunker to highlight the problem. As you can see, the data in the upper part only updates because I manually call Storage.getItems()
again after the strategy has been changed. But I cannot do that, because other component - for example OtherController
- are also accessing data on Storage
and also need to automatically get their data from the new strategy. Instead, they stay bound to the initial strategy.