我有一个填充多选的对象数组。我想在我的指令中显示所选对象,并且因为我是一个有角度的新手而遇到困难。
我想做什么
{{selectedReport.rooms | filter: {id: Vars[var.name]} }}
显示其中room.id IN Var [var.name]的selectedReport.rooms。 Var [var.name]是我的ng-model绑定。如果我选择4个报告,它可能看起来像[" 2"," 4"," 23"," 64"]
我需要根据这些ID访问selectedReport.rooms对象。我不确定如何以棱角分明的方式做到这一点。
非常感谢任何和所有帮助。
我的指令代码:
'use strict';
angular.module('lodgicalWebApp')
.directive('lodReportVariableRoomFilter', [ function ( Report, Rooms) {
return {
template: ' \
<div class="form-group" ng-show="selectedReport.rooms.length > 0"> \
<label for="{{var.name}}" class="col-sm-3 control-label">{{var.name}}</label> \
<div class="col-sm-5"> \
<select multiple="multiple" ng-model="Vars[var.name]" class="form-control"> \
<option ng-repeat="room in selectedReport.rooms track by room.id" value="{{room.id}}" >{{room.name}}</option> \
</select> \
</div> {{ selectedReport.rooms | filter: {id: Vars[var.name]} }}\
</div> \
<div class="form-group" ng-show="selectedReport.rooms.length == 0"> \
<label class="col-sm-8 control-label">Loading Rooms...</label> \
</div> \
</div>',
restrict: 'EA',
link: function(scope, element, attr){
scope.Vars[scope.var.name] = [""] ;
}
};
}]);
//example of selectedReport.rooms
selectedReport.rooms = [{id:'', name:'(all)'}, {id:'1', name:'102'}, {id:'3', name: '104c'}];
Vars [var.name]只是一个Scope变量,它包含我所有的指令输入选择。
//example of Vars[var.name]
Vars[var.name] = ['1','3'];
我想要的: 过滤后的对象:
Room [ id: '1', name: '102']
Room [ id: '3', name: '104c']
最终输出
102, 104c
答案 0 :(得分:1)
我能够创建一个自定义过滤器来实现我所需要的。
'use strict';
/**
* @ngdoc directive
* @name lodgicalWebApp.directive:lodReportVariableCgflookup
* @description
* # lodReportVariableCgflookup
*/
angular.module('lodgicalWebApp')
.directive('lodReportVariableRoomFilter', [ function ( Report, Rooms) {
return {
template: ' \
<div class="form-group" ng-show="selectedReport.rooms.length > 0"> \
<label for="{{var.name}}" class="col-sm-3 control-label">{{var.name}}</label> \
<div class="col-sm-5"> \
<select multiple="multiple" ng-model="Vars[var.name]" class="form-control"> \
<option ng-repeat="room in selectedReport.rooms track by room.id" value="{{room.id}}" >{{room.name}}</option> \
</select> \
</div> \
</div> \
<div class="form-group" ng-show="selectedReport.rooms.length == 0"> \
<label class="col-sm-8 control-label">Loading Rooms...</label> \
</div> \
<div class="form-group" ng-show="Vars[var.name].length >0"> \
<label class="col-sm-3 control-label">Selected Rooms: </label> \
<div class="col-sm-5"> \
<ul> \
<li ng-repeat = "selectedRoom in selectedReport.rooms | selectedRooms: Vars[var.name] "> \
{{ selectedRoom.name }} \
</li> \
</ul> \
</div> \
</div> \
',
restrict: 'EA',
link: function(scope, element, attr){
scope.Vars[scope.var.name] = [""] ;
}
};
}]);
过滤器:
angular.module('lodgicalWebApp').filter('selectedRooms', function() {
return function(rooms, ids) {
var filtered=[];
angular.forEach(rooms, function(v,k){
if(ids.indexOf(v.id) > -1){
filtered.push(v);
}
});
return filtered;
}
});