我有一个实用函数 notNull() 旨在与这样的过滤器一起使用:
...| filter:notNull()"
我在更多指令中需要它,这就是我将它放在 $rootScope 中的原因。
问题是我的过滤器没有被调用。我创建了一个示例 plnkr:
http://plnkr.co/edit/Nq0iLw?p=preview
有人可以帮忙吗?为什么不调用过滤器而不过滤我的项目?
附言。过滤器中的这个表达式不适用于空值:
...| filter:{myProp:!null}
最佳答案
[注意:更新按时间倒序排列。]
更新 2
首先,回答您的问题“为什么 ...| filter:{myProp:!null}
不起作用:
这是因为您尝试使用的语法(根据 the docs )仅适用于字符串值(并且 null 不是字符串值)。
您可以创建(并附加到您的应用程序)自定义过滤器:
app.filter("notEqual", function() {
return function(items, key, value) {
var filtered = [];
items.forEach(function(item) {
if (item && (item[key] !== undefined)
&& (item[key] !== value)) {
filtered.push(item);
}
});
return filtered;
};
});
然后像这样在任何指令中使用它:
...| notEqual:'<keyName>':<valueToCompareAgainst>
例如:
app.directive("mytag", function() {
return {
restrict: "E",
template: "<div ng-repeat=\"item in myModel | notEqual:'a':null\">"
+ " item: {{item}}"
+ "</div>",
scope: {
myModel: "="
}
};
});
另见其他 short demo .
更新
将服务或工厂用于实用方法可能是一个更好的主意,这些实用方法应该对许多 Controller /范围可用并且应该是可定制的。例如:
app.factory("notNullFactory", function() {
var factory = {};
factory.notNull = function(caption) {
return function(item) {
console.log(caption + " " + JSON.stringify(item));
return (item !== null);
};
};
return factory;
});
现在,您可以使用 notNullFactory
的 notNull(...)
函数来创建可自定义的过滤器函数:
app.directive("mytag", function(notNullFactory) {
return {
restrict: "E",
template: "<div>"
+ " <div ng-repeat=\"item in myModel | filter:notNull('Checking')\">"
+ " item: {{item}}"
+ " </div>"
+ "</div>",
scope: {
myModel: "="
},
link: function($scope) {
$scope.notNull = function(caption) {
return notNullFactory.notNull(caption);
};
}
};
});
另请参阅其他 short demo .
不是你的过滤器没有被调用,而是它没有被定义。在定义 $scope.notNull
时,将其设置为等于 $rootScope.notNull
,后者未定义。
相反,您可以去掉 link 属性并使用:
...| filter:$parent.notNull()...
另请参阅此 short demo .
关于javascript - angular 在过滤器中从 $rootScope 调用实用函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19706503/