所以我试图使用Angular JS和angularSoundManager模块来创建音乐播放器。我可以让歌曲和播放器工作正常,但是当我尝试将主阵列更改为每张专辑中包含一系列歌曲的专辑时,我不断收到错误,即专辑变量未定义。
app.js
angular.module('myApp', ['angularSoundManager']).controller('MainCtrl', ['$scope', function ($scope) {
$scope.albums = [
{
id: 'one',
title: 'album one',
songs : [
{
id: 'one',
title: 'Rain',
artist: 'YaNiggaPaul',
url: 'http://www.schillmania.com/projects/soundmanager2/demo/_mp3/rain.mp3'
},
{
id: 'four',
title: 'Angry cow sound?',
url: 'http://www.freshly-ground.com/data/audio/binaural/Mak.mp3'
},
{
id: 'five',
title: 'Things that open, close and roll',
url: 'http://www.freshly-ground.com/data/audio/binaural/Things%20that%20open,%20close%20and%20roll.mp3'
}
]
},
{
id: 'two',
title: 'album two',
songs : [
{
id: 'two',
title: 'Walking',
url: 'http://www.schillmania.com/projects/soundmanager2/demo/_mp3/walking.mp3'
},
{
id: 'three',
title: 'Barrlping with Carl (featureblend.com)',
url: 'http://www.freshly-ground.com/misc/music/carl-3-barlp.mp3'
}
]
}
];
}]);
模块中弹出错误的地方。
ngSoundManager.directive('playAll', ['angularPlayer', '$log',
function(angularPlayer, $log) {
return {
restrict: "EA",
scope: {
albums: '=playAll'
},
link: function(scope, element, attrs) {
element.bind('click', function(event) {
//first clear the playlist
angularPlayer.clearPlaylist(function(data) {
$log.debug('cleared, ok now add to playlist');
//add songs to playlist
for(var i = 0; i < scope.albums[attrs.alid]['songs'].length; i++) {
angularPlayer.addTrack(scope.albums[attrs.alid]['songs'][i]);
}
if (attrs.play != 'false') {
//play first song
angularPlayer.play();
}
});
});
}
};
}]);
更具体地说
scope.albums[attrs.alid]['songs'].length
错误“无法读取未定义的属性'0'。
所有的想法,我只是构建我的表错了吗? 我是Angular的新手,所以任何帮助都非常受欢迎。 &LT; 3
编辑::调用指令(我认为......?)。
<li ng-repeat="album in albums">
<button play-all="songs" my-playlist="playlist" data-alid="{{$index}}">{{album.title}}</button>
<li ng-repeat="song in album.songs">
<button music-player="play" add-song="song">{{ song.title }}</button>
</li>
</li>
答案 0 :(得分:0)
看起来您正在将歌曲列表传递给指令,而不是专辑列表。我想你想修改你的指令以接受一个专辑,并迭代它的歌曲。在这种情况下,您需要将指令调用更改为:
<button play-all="album" my-playlist="playlist">{{album.title}}</button>
然后,您需要修改指令定义以处理单个相册,而不是相册列表。您也不需要再传递相册ID,因为您已经传递了您关心的实例:
ngSoundManager.directive('playAll', ['angularPlayer', '$log',
function(angularPlayer, $log) {
return {
restrict: "EA",
scope: {
album: '=playAll'
},
link: function(scope, element, attrs) {
element.bind('click', function(event) {
//first clear the playlist
angularPlayer.clearPlaylist(function(data) {
$log.debug('cleared, ok now add to playlist');
//add songs to playlist
for(var i = 0; i < scope.album['songs'].length; i++) {
angularPlayer.addTrack(scope.album['songs'][i]);
}
if (attrs.play != 'false') {
//play first song
angularPlayer.play();
}
});
});
}
};
}]);
作为旁注 - 使用link
函数不是创建角度指令的最佳方法。 99%的指令应仅使用控制器功能并传入您需要的等效注射剂($ scope,$ element,$ attrs)。这样,你的所有指令都遵循类似的约定,因此当你深入Angular 2 +的世界时,你会更加准备