I have a ng-repeat that lists parts of the day for schedules to go into. For each line, I need to show the available playlists.
The issue that I'm having is how to match the two up so that we show the currently selected item in the drop down.
<div ng-repeat="daypart in dayparts track by $index" class="content_dayparts">
<div class="info_col_1">{{daypart.name}}</div>
<div class="info_col_2">
<select ng-model="daypart.assignment"
ng-options="p.id as p.name for p in playlists"
ng-change="assignPlaylist($index, daypart.id)">
</select></div>
When the "dayparts" change, the following function fires:
$scope.checkPlaylistAssignment = function () {
// So... We need to loop over all playlists, get their daypartId and store what it matches.
angular.forEach($scope.playlists, function(v,i) {
angular.forEach($scope.dayparts, function (vb, ib) {
if ($scope.playlists[i].daypartId == $scope.dayparts[ib].id) {
console.log("We have a match: "+$scope.playlists[i].daypartId+" Daypart Id is: "+$scope.dayparts[ib].id);
$scope.dayparts[ib].assignment = $scope.playlists[i];
} else {
console.log("Assigned Playlist is: "+$scope.playlists[i].daypartId+" Daypart Id is: "+$scope.dayparts[ib].id);
}
});
});
console.log($scope.dayparts);
}
"daypart.assignment" is set to the playlist object, but still, the assigned playlist does not show in the select. What am I missing here?
Here is a screenshot of the dev console showing that the assignment IS set.
Any help is very much appreciated. Thanks.
Although it's not the most efficient code, the code you have above for checkPlaylistAssignment
should work based on solely what you have provided in this question.
I checked the jsfiddle that you sent and I created the following checkPlaylistAssignment
which will assign the right assignment object to each daypart object when it is run.
What I'm doing is first I index the playlists by their id and then I go through each daypart and assign the right playlist object. I first created an index so that you avoid having to loop through your playlist for each single dayparts object.
$scope.checkPlaylistAssignment = function () {
var playlistIndexedById = {};
angular.forEach($scope.playlists, function (playlist){
playlistIndexedById[playlist.id] = playlist;
});
angular.forEach($scope.dayparts, function(daypart) {
var curr = daypart.assignment;
daypart.assignment = playlistIndexedById[curr.id];
});
console.log('playlistIndexedById',playlistIndexedById);
};
$scope.checkPlaylistAssignment();
I also created an updated fiddle that shows you that it works: http://jsfiddle.net/95jufwz9/12/