简单的例子。我有一个球员。分为两个部分:歌曲部分(当前播放)和播放列表部分。
我有两个控制器(实际上我会有两个控制器,这就是我为什么要问的):SongCtrl和PlalistCtrl;
但是如何在它们之间进行交互呢?例如:当我开始播放歌曲时,我还需要在播放列表中突出显示它。
发布于 2013-02-21 04:21:22
要做到这一点,最好的方法是使用服务。假设你有一个负责播放歌曲的服务(过于简化):
.factory( 'musicPlayer', function() {
var currentSongId;
// public API
return {
getCurrentSong: function () { return currentSongId; },
setCurrentSong: function ( id ) { currentSongId = id; }
};
});然后,您可以在播放列表中使用以下内容:
.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;
});
});这样你的视图就可以访问它了:
<li ng-repeat="song in songs" ng-class="{ active: isCurrentSong($index) }">
<a ng-click="play($index)">{{song.name}}</a>
</li>您可以在另一个控制器中以类似的方式访问它,以获取当前正在播放的歌曲。在没有更多细节的情况下,很难更具体,但这是最佳实践方法。
发布于 2013-02-21 04:00:58
您可以使用directives或services让控制器彼此交互。
关于你的例子:
hen I start playing song I need also highlight it inside of playlist.在这种特殊情况下,您应该避免直接从控制器更改DOM。例如,您可以使用directive来突出显示播放列表中正在播放的歌曲,
https://stackoverflow.com/questions/14988760
复制相似问题