我在多个 View 上使用元素指令。该指令对资源列表中的每个“资源”重复,如下所示:ng-repeat="resource in resources"
。
不同的页面 Controller 将通过在每个 View Controller 中使用不同的 $scope.resourceApiPath
来确定从 API 中提取哪些资源,然后指令 Controller 使用该 View Controller 来创建 $http
调用。
这对于显示不同资源的不同 View 非常有效。例如一个 View 显示用户自己的所有资源,一个 View 显示公共(public)资源,一个 View 显示用户已加星标的资源等。
唯一的问题是,对于我的一个 View ,我想在 ng-repeat
上添加一个过滤器,如下所示:ng-repeat="resource in resources | filter:resourceSearch。文本”
。有没有办法让我根据条件添加此过滤器,例如if $scope.filter == true;
,否则仅返回常规 ng-repeat="resource in resources"
?
这是我的指令:
.directive('resourcePanel', function() {
return {
restrict: 'E',
scope: false,
templateUrl: 'scripts/templates/resource-panel.html',
controller: 'ResourcesPanelController'
}
})
指令中引用的ResourcesPanelController
具有如下内容:
$scope.resources = [];
$scope.loadResources = function() {
$scope.resources = []; // Empty the array
$http.get('/api/resource' + $scope.resourceApiPath)
.then(function(res) {
$scope.resources = res.data.message;
});
};
$scope.loadResources();
scripts/templates/resource-panel.html
元素模板看起来像这样:
<div class="panel" ng-repeat="resource in resources">
{{resource.content}}
</div>
谢谢!
最佳答案
我认为您可以采用四种方法之一,我更喜欢 1 和 3,但这完全取决于您的要求和代码标准,哪一种最适合您。
自定义过滤器也是一个干净的解决方案。
如果您使用文本值进行过滤,那么如果您没有设置resourceSearch.text的值,那么它就和没有过滤一样好,所以如果resourceSearch.text存在,它将过滤,如果它未定义,那么无过滤器。
ng-repeat="资源中的资源 | 过滤器:resourceSearch.text"
创建自定义过滤器并在那里处理它。
如果您想创建自定义过滤器,请使用启用参数,您可以使用它来打开和关闭过滤器 http://plnkr.co/edit/ilPJPUZkBC7Y5OvGHWey?p=preview我还找到了一个适合您需要的自定义过滤器 plunkr
ng-repeat="resource in resources | customfilter:resourceSearch.text:enable"
在 Controller 中过滤最终资源并将过滤后的值传递给 html
将 ng-if 与您的条件一起使用,如果过滤器存在,则进行一个循环,如果不存在,则进行不同的循环。
希望对您有所帮助。
关于javascript - 如何有条件地将过滤器添加到 ng-repeat inside 指令?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37310227/