我已经写了一个过滤器函数,它将根据您传递的参数返回数据。我希望在控制器中有相同的功能。是否有可能在控制器中重用过滤器函数?
这是我目前为止尝试过的:
function myCtrl($scope,filter1)
{
// i simply used the filter function name, it is not working.
}
我已经写了一个过滤器函数,它将根据您传递的参数返回数据。我希望在控制器中有相同的功能。是否有可能在控制器中重用过滤器函数?
这是我目前为止尝试过的:
function myCtrl($scope,filter1)
{
// i simply used the filter function name, it is not working.
}
当前回答
在控制器中使用$filter的简单日期示例如下:
var myDate = new Date();
$scope.dateAsString = $filter('date')(myDate, "yyyy-MM-dd");
正如这里解释的- https://stackoverflow.com/a/20131782/262140
其他回答
如果我们想在javascript角过滤器中添加多个条件,而不是单个值,请使用下面的代码:
var modifiedArray = $filter('filter')(array,function(item){return (item.ColumnName == 'Value1' || item.ColumnName == 'Value2');},true)
在控制器中使用$filter的简单日期示例如下:
var myDate = new Date();
$scope.dateAsString = $filter('date')(myDate, "yyyy-MM-dd");
正如这里解释的- https://stackoverflow.com/a/20131782/262140
重用Angular.js的过滤器-视图/控制器
这个解决方案涵盖了重用Angular过滤器。这是过滤数据的另一种方式,当我需要这样的时候,谷歌让我来到这里;我喜欢分享。
用例
如果你已经过滤了,比如在你的视图中使用ng-repeat(如下所示),那么你可能已经在控制器中定义了一个过滤器,如下所示。然后你可以像在最后的例子中那样重用。
过滤器使用示例-视图中已过滤重复
<div ng-app="someApp" ng-controller="someController">
<h2>Duplicates</h2>
<table class="table table-striped table-light table-bordered-light">
<thead>
<tr>
<th>Name</th>
<th>Gender</th>
</tr>
</thead>
<tbody>
<tr ng-repeat="person in data | filter: searchDuplicate:true">
<td>{{person.name}}</td>
<td>{{person.gender}}</td>
</tr>
</tbody>
</table>
</div>
Angular过滤器定义示例
angular.module('someApp',[])
.controller('someController', function($scope, $filter ) {
$scope.people = [{name: 'Bob', gender: 'male' , hasDuplicate: true },
{name: 'Bob', gender: 'male' , hasDuplicate: true },
{name: 'Bob', gender: 'female', hasDuplicate: false}];
$scope.searchDuplicate = { hasDuplicate : true };
})
这里的概念是,你已经在使用为视图创建的过滤器,然后意识到你也想在控制器中使用它。
在控制器内使用Filter函数示例1
var dup = $filter('filter')($scope.people, $scope.searchDuplicate, true)
例2:在控制器中使用Filter函数
使用优先筛选器,仅在没有找到重复项时显示按钮。
Html按钮
<div ng-if="showButton()"><button class="btn btn-primary" ng-click="doSomething();"></button></div>
显示/隐藏按钮
$scope.doSomething = function(){ /* ... */ };
$scope.showButton = function(){ return $filter('filter')($scope.people, $scope.searchDuplicate, true).length == 0; };
有些人可能会发现这个版本的过滤很简单,它是一个Angular.js选项。
视图和$filter函数调用中使用的可选比较器参数“true”指定需要严格比较。如果省略,则可以在多个列中搜索值。
https://docs.angularjs.org/api/ng/filter/filter
首先注入$filter到你的控制器中,确保ngSanitize被加载到你的应用中,随后在控制器中使用如下:
$filter('linky')(text, target, attributes)
经常查看angularjs的文档
注入$filter到你的控制器
function myCtrl($scope, $filter)
{
}
然后无论你想在哪里使用这个过滤器,就像这样使用它:
$filter('filtername');
如果你想把参数传递给这个过滤器,使用单独的括号:
function myCtrl($scope, $filter)
{
$filter('filtername')(arg1,arg2);
}
其中arg1是要筛选的数组,arg2是用于筛选的对象。