我已经写了一个过滤器函数,它将根据您传递的参数返回数据。我希望在控制器中有相同的功能。是否有可能在控制器中重用过滤器函数?

这是我目前为止尝试过的:

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

其他回答

注入$filter到你的控制器

function myCtrl($scope, $filter)
{
}

然后无论你想在哪里使用这个过滤器,就像这样使用它:

$filter('filtername');

如果你想把参数传递给这个过滤器,使用单独的括号:

function myCtrl($scope, $filter)
{
    $filter('filtername')(arg1,arg2);
}

其中arg1是要筛选的数组,arg2是用于筛选的对象。

首先注入$filter到你的控制器中,确保ngSanitize被加载到你的应用中,随后在控制器中使用如下:

$filter('linky')(text, target, attributes)

经常查看angularjs的文档

function ngController($scope,$filter){
    $scope.name = "aaaa";
    $scope.age = "32";

     $scope.result = function(){
        return $filter('lowercase')($scope.name);
    };
}

控制器方法的第二个参数名称应该是“$filter”,那么只有过滤器功能将适用于这个例子。在这个例子中,我使用了“小写”过滤器。

似乎没有人提到你可以在$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.");

很简单吧?