angularjs - How to call the same directive in different views through one controller -
i have 1 directive looks this
.directive('audioplay', function() { return { restrict: 'e', link: function(scope, element, attr) { var player = element.children('.player')[0]; scope.playorpause = true; scope.playmusic = function() { scope.playorpause = false; player.play(); } scope.stopmusic = function() { scope.playorpause = true; player.pause(); } } }; })
i using directive play , pause audio
<audio-play> <audio class="player"> <source src="http://fire.wavestreamer.com:9711/urbanetradio"/> </audio> <button ng-click="playmusic()" ng-hide="!playorpause"> </button> <button ng-click="stopmusic()" ng-show="!playorpause"> </button> </audio-play>
this app need have audio in every view, doesn't matter user goes, live streaming should there.
i have controller attached tabs abstract view, controller everywhere user goes, need call directive , attache controller, how can ?
i'm afraid answers problem (that don't involve restructuring html hierarchy) dirty.
1) use $rootscope instead of scope. can inject things in directives, redefine directive as:
.directive('audioplay', function($rootscope) { return { restrict: 'e', link: function(scope, element, attr) { var player = element.children('.player')[0]; $rootscope.playorpause = true; $rootscope.playmusic = function() { $rootscope.playorpause = false; player.play(); } $rootscope.stopmusic = function() { $rootscope.playorpause = true; player.pause(); } } }; })
that's dirty because don't want throwing things on $rootscope unless have to. it's window
. it's global angular app , gets cluttered quickly.
2) manually grab scope you're interested in.
.directive('audioplay', function($rootscope) { return { restrict: 'e', link: function(scope, element, attr) { var $scope = $('[ng-controller="whatevercontroller"]').scope(); var player = element.children('.player')[0]; $scope.playorpause = true; $scope.playmusic = function() { $scope.playorpause = false; player.play(); } $scope.stopmusic = function() { $scope.playorpause = true; player.pause(); } } }; })
this dirty . . . just, dirty shouldn't have been spoken out loud.
is there reason can't put playmusic
, stopmusic
on actual scope inside controller? seems bad idea me defining new functions on scope inside directive.
Comments
Post a Comment