如何使用ng-options迭代对象中的数组?

时间:2015-07-17 16:37:37

标签: javascript angularjs

如何使用ng-options用对象中的“categories”数组的结果填充select元素?

        {
          title: "Star Wars",
          categories: ["Coding", "Exploration", "Adventure"]
        }, {
          title: "Street Wars",
          categories: ["Surfing", "Exploration", "Testing"]
        },

我想填充一个包含所有可用类别的select元素,然后使用“unique”来过滤掉重复的条目......

2 个答案:

答案 0 :(得分:2)

正如评论所说,在控制器中创建唯一部件可能更容易,并在新阵列上使用ngOptions

$scope.uniqueOptions = [];
for (var i = 0; i < data.length; i++) {
    for (var j = 0; j < data[i].categories.length; j++) {
        if ($scope.uniqueOptions.indexOf(data[i].categories[j]) === -1) {
            $scope.uniqueOptions.push(data[i].categories[j])
        }
    }
}

选项:

<select ng-model="someModel" ng-options="category as category for category in uniqueOptions"> </select>

答案 1 :(得分:1)

如果您使用的是ngRepeat

,则可以这样做
 <select ng-model="cat" ng-options="c for c in movie.categories"></select>

@Guillermo Winkler's answer

编辑:选择时需要ngModel。

相关问题