Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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.

like image 874
ValeriiVasin Avatar asked Feb 20 '13 19:02

ValeriiVasin


People also ask

Can we have two controllers in AngularJS?

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.

How can we share the data between controllers in AngularJS?

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.

Can we inject one controller into another controller in AngularJS?

You can't inject controllers into one another. Yes, you should change TestCtrl1 into a service instead.


1 Answers

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.

like image 69
Josh David Miller Avatar answered Sep 17 '22 23:09

Josh David Miller