【发布时间】:2016-06-14 12:36:51
【问题描述】:
我讨厌重复代码。所以我想知道是否有更好的方法来做到这一点。 我有 2 个指令,它们非常简单且非常相似。 这 2 个指令如下所示:
.directive('pkFilterProducts', function () {
return {
restrict: 'A',
templateUrl: 'assets/templates/directives/pkFilterProducts.html',
scope: {
products: '=pkFilterProducts',
filters: '='
}
}
})
.directive('pkStateProducts', function () {
return {
restrict: 'A',
templateUrl: 'assets/templates/directives/pkStateProducts.html',
scope: {
products: '=pkStateProducts',
states: '='
}
}
})
唯一的区别是一个接受过滤器,另一个接受状态。 模板也非常相似:
<div class="col-md-6">
<h3>Excluded ({{ excluded.length }})</h3>
<div class="table-responsive" ng-show="excluded.length">
<table class="table table-hover">
<thead>
<tr>
<th class="image-column"></th>
<th>Title</th>
</tr>
</thead>
<tbody>
<tr ng-repeat="product in products | exclude: filters as excluded">
<td><img class="img-responsive" ng-src="{{ product.image }}" /></td>
<td>{{ product.shortTitle }}</td>
</tr>
</tbody>
</table>
</div>
</div>
<div class="col-md-6">
<h3>Included ({{ included.length }})</h3>
<div class="table-responsive" ng-show="included.length">
<table class="table table-hover">
<thead>
<tr>
<th class="image-column"></th>
<th>Title</th>
</tr>
</thead>
<tbody>
<tr ng-repeat="product in products | include: filters as included">
<td><img class="img-responsive" ng-src="{{ product.image }}" /></td>
<td>{{ product.shortTitle }}</td>
</tr>
</tbody>
</table>
</div>
</div>
和
<div class="col-md-6">
<h3>Excluded ({{ excluded.length }})</h3>
<div class="table-responsive" ng-show="excluded.length">
<table class="table table-hover">
<thead>
<tr>
<th class="image-column"></th>
<th>Title</th>
</tr>
</thead>
<tbody>
<tr ng-repeat="product in products | statesExclude: states as excluded">
<td><img class="img-responsive" ng-src="{{ product.image }}" /></td>
<td>{{ product.shortTitle }}</td>
</tr>
</tbody>
</table>
</div>
</div>
<div class="col-md-6">
<h3>Included ({{ included.length }})</h3>
<div class="table-responsive" ng-show="included.length">
<table class="table table-hover">
<thead>
<tr>
<th class="image-column"></th>
<th>Title</th>
</tr>
</thead>
<tbody>
<tr ng-repeat="product in products | statesInclude: states as included">
<td><img class="img-responsive" ng-src="{{ product.image }}" /></td>
<td>{{ product.shortTitle }}</td>
</tr>
</tbody>
</table>
</div>
</div>
同样,唯一不同的是 ng-repeat 过滤器。它不使用 include 或 exclude,而是使用 statesInclude 和 statesExclude。 有没有办法我也可以结合这些?也许为过滤器使用一个变量?
【问题讨论】:
-
您不能为过滤器使用变量。除非您想重构过滤器并创建接受“模式”参数并聚合
include和stateInclude的自定义过滤器,否则没有,没有办法。而且,代码不会因为重构而哭泣,我认为没有理由用凌乱的公分母来破坏它。 -
stackoverflow.com/questions/26710513/… 显示使用过滤器名称作为变量
-
它本质上和自定义过滤器是一样的,只是更别扭。
标签: angularjs