Simple example. I have a player. It's divided into 2 sections: song section (currently playing) and playlist section.
I have 2 controllers (Actulally I'm going to have 2 controllers, that is why i'm asking): SongCtrl and PlalistCtrl;
But how to interact between them? for example: when I start playing song I need also highlight it inside of playlist.
An AngularJS application can contain one or more controllers as needed, in real application a good approach is to create a new controller for every significant view within the application. This approach will make your code cleaner and easy to maintain and upgrade. Angular creates one $scope object for each controller.
Approach: To share data between the controllers in AngularJS we have two main cases: Share data between parent and child: Here, the sharing of data can be done simply by using controller inheritance as the scope of a child controller inherits from the scope of the parent controller.
You can't inject controllers into one another. Yes, you should change TestCtrl1 into a service instead.
The best way to do this is with a service. Let's say you have a service responsible for playing the songs (over-simplified):
.factory( 'musicPlayer', function() {
var currentSongId;
// public API
return {
getCurrentSong: function () { return currentSongId; },
setCurrentSong: function ( id ) { currentSongId = id; }
};
});
You can then use this in your playlist:
.controller( 'PlaylistCtrl', function ( $scope, musicPlayer ) {
$scope.isCurrentSong = function( idx ) {
if ( $scope.currentSong == idx ) return true;
};
$scope.play = function( idx ) {
musicPlayer.setCurrentSong( idx );
};
$scope.$watch( function () {
return musicPlayer.getCurrentSong()
}, function ( id ) {
$scope.currentSong = id;
});
});
So your view could then access it:
<li ng-repeat="song in songs" ng-class="{ active: isCurrentSong($index) }">
<a ng-click="play($index)">{{song.name}}</a>
</li>
And you would access it similarly in your other controller to get the current playing song. Without more detail, it's hard to be more specific, but this is the best practice approach.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With