2013-02-20 28 views
6

簡單的例子。我有一個球員。它分爲2個部分:歌曲部分(正在播放)和播放列表部分。我有2個控制器(Actulally我將有2個控制器,這就是爲什麼我問):SongCtrl和PlalistCtrl;如何在AngularJS中的不同控制器之間進行交互

但是如何在它們之間進行交互?例如:當我開始播放歌曲時,我還需要在播放列表中突出顯示它。

回答

1

您可以讓控制器使用directivesservices相互作用。

關於你提到的例子:

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

在你應該避免直接從控制器改變DOM這種特殊情況。例如,您可以使用directive來突出顯示播放列表中正在播放的歌曲,

+0

你是什麼意思?我不會從控制器中改變某些東西。去使用ng-class。 – ValeriiVasin 2013-02-20 20:12:01

+0

這實際上就是我的意思,使用'ng-class'而不是從控制器添加javascript。此外,你可能想重新考慮有一個單一的控制器,它會簡化的事情。你仍然可以有專門的服務(一個用於歌曲,另一個用於播放列表) – Ulises 2013-02-20 20:16:03

+0

我也喜歡這種方法。會考慮一下。也有人分享如何「Angular-way」做共享:)也謝謝你的迴應。 – ValeriiVasin 2013-02-20 20:20:29

9

執行此操作的最佳方法是使用服務。比方說,你必須負責播放歌曲(過於簡單化)服務:

.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> 

而你也同樣訪問它在你的其他控制器,以獲得當前播放的歌曲。沒有更多的細節,很難更具體,但這是最佳實踐方法。

+0

非常感謝!它看起來像我的播放器:D我不知道有2個函數作爲參數的$ watch語法,但我會發現! – ValeriiVasin 2013-02-20 20:31:08

相關問題