【问题标题】:How to Use Filter Passed from Controller in Directive Link Function如何在 Directive Link 函数中使用从控制器传递的过滤器
【发布时间】:2016-05-10 20:53:45
【问题描述】:

我有一个过滤器,我想在指令中使用它。 我有一个简单的过滤器,可以在 ng-repeat 指令中正常工作 我不太确定如何在指令链接函数中应用。 我写了下面的指令,将过滤器作为一个函数,这是正确的方法,我该怎么做?还是有更好的方法?

JavaScript

myApp.directive('repeatDirective', ['$filter', function($filter) {
    return {
        scope: {
            'filter': '&?',
            'itemList': '='
        },
        template: "<div ng-repeat='item in itemList'>{{item .name}}</div>",
        link: function (scope,element,attrs, ngModelCtrl) {
           **// how to  filter itemList here???**
        }
    };
}]);

过滤

$rootScope.collectionFilter= function (transType) {
if($scope.formData_EventDetails.actualPotential){
    if($scope.formData_EventDetails.actualPotential=='NM'){
        //console.log(transType.tranTypeName.indexOf('Near Miss'));

        return transType.tranTypeName.indexOf('Near Miss') >=0 ;
    }
    else{
        return transType.tranTypeName.indexOf('Near Miss') <0 ;
    }
}
return true;
};

HTML

<repeat-directive item-list="someObjectCollection" filter="collectionFilter()">
</repeat-directive>

【问题讨论】:

  • 最好的方法是在你的应用程序中定义过滤器,然后将其注入指令并以这种方式使用它。然后你可以将它定义为它自己的实体,并在需要的地方使用它

标签: javascript angularjs angularjs-directive angularjs-scope angularjs-filter


【解决方案1】:

使用 Angular 的注册过滤器方法定义您的过滤器,然后像使用内置过滤器一样使用。如果您有任何问题,请告诉我。

过滤器:

myApp.filter('collectionFilter', function(){
  return function(input){
    return input ? 'true : 'false';
  };
});

【讨论】:

  • 问题不是关于如何编写过滤器,而是关于如何在作为函数传入的指令链接函数中使用它
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2016-05-28
  • 1970-01-01
  • 2014-05-12
  • 2023-03-24
  • 2019-04-20
  • 2012-12-27
相关资源
最近更新 更多