ng-repeat中的嵌套ng-options - 如何选择?

时间:2014-10-28 16:14:57

标签: javascript angularjs ng-repeat ng-options

我有一个ng-repeat,列出了当天的部分时间表。对于每一行,我需要显示可用的播放列表。

我遇到的问题是如何匹配这两个,以便我们在下拉列表中显示当前选定的项目。

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

当“dayparts”发生变化时,会触发以下功能:

$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”设置为播放列表对象,但仍然,分配的播放列表不会显示在选择中。我在这里缺少什么?

以下是开发控制台的屏幕截图,显示已设置分配。

Here is a screenshot of the dev console showing that the assignment IS set.

非常感谢任何帮助。感谢。

1 个答案:

答案 0 :(得分:2)

虽然它不是最有效的代码,但您在checkPlaylistAssignment上面的代码应该仅基于您在此问题中提供的内容。

我检查了你发送的jsfiddle并创建了以下checkPlaylistAssignment,它将在运行时为每个daypart对象分配正确的赋值对象。

我要做的是首先按照他们的ID索引播放列表然后我浏览每个时段并分配正确的播放列表对象。我首先创建了一个索引,以便您不必为每个单个时段对象循环播放播放列表。

$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();

我还创建了一个更新的小提示,向您展示它的工作原理:http://jsfiddle.net/95jufwz9/12/