ValeriiVasin
ValeriiVasin

Reputation: 8706

How to interact between different controllers in AngularJS

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.

Upvotes: 6

Views: 4576

Answers (2)

Josh David Miller
Josh David Miller

Reputation: 120513

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.

Upvotes: 9

Ulises
Ulises

Reputation: 13419

You could have the controllers interact with each other using directives or services.

Regarding your example:

hen I start playing song I need also highlight it inside of playlist.

In this particular case you should avoid changing the DOM directly from the controllers. For example, you could have a directive that highlights the song being played in the playlist,

Upvotes: 1

Related Questions