我已经写了一个过滤器函数,它将根据您传递的参数返回数据。我希望在控制器中有相同的功能。是否有可能在控制器中重用过滤器函数?
这是我目前为止尝试过的:
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.
}
当前回答
如果你想在控制器中过滤对象,试试这个
var rateSelected = $filter('filter')($scope.GradeList, function (obj) {
if(obj.GradeId == $scope.contractor_emp.save_modal_data.GradeId)
return obj;
});
这将根据if条件返回过滤后的对象
其他回答
如果你想在控制器中过滤对象,试试这个
var rateSelected = $filter('filter')($scope.GradeList, function (obj) {
if(obj.GradeId == $scope.contractor_emp.save_modal_data.GradeId)
return obj;
});
这将根据if条件返回过滤后的对象
还有另一种方法来计算从视图中镜像语法的过滤器。调用是复杂的,但您可以构建到它的快捷方式。我喜欢这个字符串的语法和视图中的是一样的。看起来是这样的:
function myCtrl($scope, $interpolate) {
$scope.$eval($interpolate( "{{ myvar * 10 | currency }} dollars." ))
}
如果我们想在javascript角过滤器中添加多个条件,而不是单个值,请使用下面的代码:
var modifiedArray = $filter('filter')(array,function(item){return (item.ColumnName == 'Value1' || item.ColumnName == 'Value2');},true)
首先注入$filter到你的控制器中,确保ngSanitize被加载到你的应用中,随后在控制器中使用如下:
$filter('linky')(text, target, attributes)
经常查看angularjs的文档
重用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