Create a service for directives to utilize and maintain the state within it.
Here is an example implementation:
angular.module('MyPlayer' [])
.factory('playerState', function() {
var players = [];
return {
registerPlayer: function(player) {
players.push(player);
},
unregisterPlayer: function(player) {
var index = players.indexOf(player);
(index>-1) && players.splice(index, 1);
},
stopAllPlayers: function() {
for(var i=0; i<players.length; i++) {
players[i].stop();
}
}
}
})
.directive('player', function(playerState) {
return {
...
link: function(scope, elem, attr) {
var player = {
stop: function() {
/* logic to stop playback */
},
play: function(song) {
playerState.stopAllPlayers();
/* logic to start playing */
}
}
playerState.registerPlayer(player);
scope.$on("$destroy", function() {
playerState.unregister(player);
});
scope.play = player.play;
scope.stop = player.stop;
...
}
}
})