How to interact between different controllers in AngularJS

angularjs, javascript

Solution

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.

Problem

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.

Original source