我有带过滤器的Angular JS代码:
.filter('filterSelectOptionAllowed', function () {
var allowed = {1: [0, 1, 2, 3, 4], 2: [0, 1, 2, 3, 4], 3: [1, 2, 3, 4]};
var d = {};
return function (num, account) {
angular.forEach(num, function (item, key) {
var arrElem = allowed[account];
if (arrElem.indexOf(key) > -1) {
d[key] = item;
}
});
return d;
};
});
acount
是3。
所以,我检查数组key
中是否存在arrElem
我将此元素添加到对象d
。
为什么我得到空对象d
?
我也试过了:
return function (num, account) {
var arrElem = allowed[account];
angular.forEach(num, function (item, key) {
if ($.inArray(parseInt(key), arrElem ) > -1 ){
d[key] = item;
}
});
return d;
};
答案 0 :(得分:0)
正如评论中所提到的,key是一个字符串,因此您需要使用indexOf
为parseInt
方法输入它。
请查看下面的演示或fiddle。我不确定输入数据是否正确,因为您还没有在问题中添加它,但过滤器现在会返回一个对象。
angular.module('demoApp', [])
.controller('MainController', MainController)
.filter('filterSelectOptionAllowed', function () {
var allowed = {1: [0, 1, 2, 3, 4], 2: [0, 1, 2, 3, 4], 3: [1, 2, 3, 4]};
var d = {};
return function (num, account) {
console.log(num, account);
var arrElem = allowed[account];
angular.forEach(num, function (item, key) {
//console.log('arrel', arrElem, key, arrElem.indexOf(key), item, typeof key);
if (arrElem.indexOf(parseInt(key)) > -1) {
console.log('item', item);
d[key] = item;
}
});
return d;
};
});
function MainController($filter) {
var elements = this.input = {0: "name", 1: "name2", 3: "name3"};
console.log($filter('filterSelectOptionAllowed')(elements, 3));
}

<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>
<div ng-app="demoApp" ng-controller="MainController as ctrl">
input data: {{ctrl.input}}<br/>
filtered: {{ctrl.input | filterSelectOptionAllowed: 3}}
</div>
&#13;