CharlieShi CharlieShi - 1 month ago 14
AngularJS Question

Multiple directives in a controller, only one can display at any time

I have a controller here and two directives:

app.controller('ListCtrl', function($scope){
$scope.audioOptions = {
audio: [{
file : "sound/world.mp3",
type: "mp3"
},
{
file : "sound/world.ogg",
type: "ogg"
}],
playOnclick : true,
playOnload: true
};
$scope.textOptions={
text : "Bird",
audio: [
{
file : "sound/world.mp3",
type: "mp3"
},
{
file : "sound/world.ogg",
type: "ogg"
}],
playAudioOnClick : true
};
});

app.directive('rsTextComponent',['ngAudio',function(ngAudio){
return {
restrict:'E',
replace:true,
scope:{options:"=options"},
controller:function($scope){
//click to play
$scope.playTextAudio = function(){
if($scope.options.playAudioOnClick)
{
ngAudio.play(audioCurrent);
}
}
},
template:'<div class="textbar" ng-click="playTextAudio()">{{options.text}}</div>'
};
}]);

app.directive('rsAudioComponent',['ngAudio',function(ngAudio){
return {
restrict:'E',
replace:true,
scope:{options:"=options"},
controller:function($scope){
//click to play
$scope.playAudio = function(){
if($scope.options.playOnclick)
{
ngAudio.play(audioCurrent);
}
}
},
template:'<div class="audiobar"><button ng-click="playAudio()">PLAY</button></div>'
};
}]);


Then I render it in list.html:

<div ng-controller="ListCtrl">
<rs-audio-component options="audioOptions">
<rs-text-component options="textOptions">
</div>


Seems all are ok, but the problem here is that, when I start to browse list.html, only one directive can render and display, the other one disappears. it's wired.
Below are the steps I tested:

When I comment out the rs-audio-component element and keep rs-text-component in list.html, then rs-text-component works properly.

When I comment out the rs-text-component element and keep rs-audio-component in list.html, then rs-audio-component works properly.

But when I keep them two in list.html, only rs-audio-component can display, rs-text-component disappears.

Would anyone give some light? thx.

Answer

You need to close the directive tags. It is the XML way. <rs-audio-component></rs-audio-component>

Comments