我已经写了一个过滤器函数,它将根据您传递的参数返回数据。我希望在控制器中有相同的功能。是否有可能在控制器中重用过滤器函数?
这是我目前为止尝试过的:
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('filtername')(arg1,arg2)中使用函数arg2;
例如:
$scope.filteredItems = $filter('filter')(items, function(item){return item.Price>50;});
其他回答
首先注入$filter到你的控制器中,确保ngSanitize被加载到你的应用中,随后在控制器中使用如下:
$filter('linky')(text, target, attributes)
经常查看angularjs的文档
还有另一种方法来计算从视图中镜像语法的过滤器。调用是复杂的,但您可以构建到它的快捷方式。我喜欢这个字符串的语法和视图中的是一样的。看起来是这样的:
function myCtrl($scope, $interpolate) {
$scope.$eval($interpolate( "{{ myvar * 10 | currency }} dollars." ))
}
似乎没有人提到你可以在$filter('filtername')(arg1,arg2)中使用函数arg2;
例如:
$scope.filteredItems = $filter('filter')(items, function(item){return item.Price>50;});
下面是在Angular控制器中使用过滤器的另一个例子:
$scope.ListOfPeople = [
{ PersonID: 10, FirstName: "John", LastName: "Smith", Sex: "Male" },
{ PersonID: 11, FirstName: "James", LastName: "Last", Sex: "Male" },
{ PersonID: 12, FirstName: "Mary", LastName: "Heart", Sex: "Female" },
{ PersonID: 13, FirstName: "Sandra", LastName: "Goldsmith", Sex: "Female" },
{ PersonID: 14, FirstName: "Shaun", LastName: "Sheep", Sex: "Male" },
{ PersonID: 15, FirstName: "Nicola", LastName: "Smith", Sex: "Male" }
];
$scope.ListOfWomen = $scope.ListOfPeople.filter(function (person) {
return (person.Sex == "Female");
});
// This will display "There are 2 women in our list."
prompt("", "There are " + $scope.ListOfWomen.length + " women in our list.");
很简单吧?
在控制器中使用$filter的简单日期示例如下:
var myDate = new Date();
$scope.dateAsString = $filter('date')(myDate, "yyyy-MM-dd");
正如这里解释的- https://stackoverflow.com/a/20131782/262140