我正在构建一个事件应用程序,它使用 Drupal 中的 JSON 在 AngularJS 中显示事件(在 Drupal 模块内)。 JSON 对象键之一是“流派”,我在选择下拉列表中使用它,以便用户可以按流派过滤事件。
我尝试过 ng-option 和 ng-repeat 方法来填充选择,我发现只有 ng-repeat 有效,但当然它为具有特定流派的事件的每个实例添加了一个选项 -因此,如果我有两个音乐事件,我会在选择中得到两个音乐选项。所以现在我正在尝试删除重复项。
我尝试过 ui.unique 但删除了除其中一个选项之外的所有选项,而不是重复项。我也尝试过自定义过滤器并遇到类似的问题。我认为数据或 AngularJS 应用程序的结构很奇怪,所以最好尝试一个指令,但我在没有 JQuery 的情况下迷失了,需要帮助!我愿意接受任何建议。
JSON
{"nodes":[
{"node":{
"title":"The Awesome Band",
"date":"2015-03-14T00:00:00+00:00",
"venue":"The Place",
"image":{
"src":"/images/band.jpg",
"alt":"The Awesome Band at The Place"
},
"time":"8pm",
"taxonomy":"Rock",
"genre":"Music Event"
}
}]}
JS
var weekEvents = angular.module('weekEvents',[]);
jQuery(document).ready(function(){
angular.bootstrap(document.getElementById('weekEvents-app'), ['weekEvents']);
});
var weekEventsController = function($scope, $http){
$http.get('/json/next7days').success(function(result){
$scope.weekEvents = (function(){
return result.nodes;
})();
});
};
weekEvents.directive('genreSelect', function(){
return{
restrict: "AE",
link:function(scope, elem, attrs){
elem.slice.call(elem.options)
.map(function(a){
if(this[a.value]){
elem.removeChild(a);
} else {
this[a.value]=1;
}
},{});
}
}
});
HTML
<div id="weekEvents-app">
<div class="col-md-8 col-sm-8" ng-controller="weekEventsController">
<h2>This week</h2>
<select ng-model="showGenre" name="genreSelect" data-genre-select>
<option value="All" selected>All</option>
<option ng-repeat="event in weekEvents" value="{{event.node.genre}}">{{event.node.genre}}</option>
</select>
<div class="mainEventItem" ng-repeat="event in weekEvents | orderBy:sortOrder | filter:showGenre">
<main-item-container>
<div class="mainItem" ng-click="expandItem()">
<img src="{{event.node.image.src}}" alt="{{event.node.image.alt}}" class="img-responsive mainItemImg"/>
<div class="mainItemDetails">
<h2 class="eventTitle">{{event.node.title}}</h2>
<p class="eventDate">{{event.node.date | date: 'EEEE'}} / {{event.node.field_time}} / {{event.node.venue}}</p>
</div>
<div class="animate-show mainItemDesc lightLink" ng-show='!collapsed'>
<p><strong>{{event.node.venue}} | {{event.node.cost}}</strong></p>
<p>{{event.node.description}}</p>
<a ng-href="{{event.node.Path}}">MORE</a>
</div>
</main-item-container>
</div>
</div>
</div>
最佳答案
一种简单的方法,可能不是最有效的,特别是对于大数组,但你明白了:
$scope.getWeekEventsGenres = function() {
return $scope.weekEvents.map(function (event) {
return event.node.genre;
})
//maybe sort?
.sort()
//remove duplicates
.filter(function(item, pos) {
return a.indexOf(item) == pos;
});
}
<option ng-repeat="event in getWeekEventsGenres()" ...>...</option>
关于javascript - 使用 AngularJS 指令从 select 中删除重复项,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29019104/