AngularJS: Communication between directives

前端 未结 4 848
时光说笑
时光说笑 2021-01-01 05:33

I\'m writing a directive which creates an mp3/audio player. The issue is that you can have many audio players in one page. What I would like to do is when one is playing and

4条回答
  •  感情败类
    2021-01-01 06:08

    Make a service that each directive uses and hold the state in there.

    Something like this:

    angular.module('MyPlayer' [])
    .factory('playerState', function() {
        var players = [];
        return {
            registerPlayer: function(player) {
                players.add(player);
            },
            unregisterPlayer: function(player) {
                var i = players.indexOf(player);
                (i>-1) && players.splice(i,1);
            },
            stopAllPlayers: function() {
                for(var i=0;i
    .directive('player', function(playerState) {
        return {
            ...
            link: function(scope, elem, attr) {
                var player = {
                    stop: function() {
                        /* logic to stop playing */
                    },
                    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;
    
                ...
            }
        }
    })
    

提交回复
热议问题