2016-01-20 72 views
1

我有一个自定义指令,我希望能够将过滤器名称传递给它。该过滤器将在我的模板中使用。以下是我走到这一步:如何将过滤器传递到AngularJS中的指令

指令:

angular.module('forecastDirective', []) 
.directive('forecast', ['appConfig', function(appConfig) { 
    return { 
     templateUrl: appConfig.directivesRoot + 'templates/forecast.html', 
     replace: true, 
     scope: { 
      weatherObject: "=", 
      convertToDate: "&", 
      filterTemp: "@", 
      dateFormat: "@", 
     }, 
    } 
}]); 

模板:

<div class="panel panel-default"> 
    <div class="panel-heading"> 
     <h3 class="panel-title">{{ convertToDate({ dt: weatherObject.dt }) | date: dateFormat }}</h3> 
    </div> 
    <div class="panel-body"> 
     Daytime temperature: {{ weatherObject.temp.day | filterTemp }} 
    </div> 
</div> 
+0

作为@ AmyBlankenship的回答状态,您不需要将其注入或传递给指令定义。它应该可用于模板。如果不是,那么您可能需要检查该过滤器是否适用于您的指令所定义的模块。 – jusopi

回答

1

一个非常简单的方法是,使用$filter服务和范围的功能委托给正确的过滤器:

angular.module('forecastDirective', []) 
.directive('forecast', ['appConfig', function(appConfig) { 
    return { 
     templateUrl: appConfig.directivesRoot + 'templates/forecast.html', 
     replace: true, 
     scope: { 
      weatherObject: "=", 
      convertToDate: "&", 
      filterTemp: "@", 
      dateFormat: "@", 
     }, 
     controller: ['$filter', '$scope', function($filter, $scope) { 
      $scope.filterFn = function(in) { 
       return $filter($scope.filterTemp)(in); 
      }; 
     } 
    } 
}]); 

一个缺点是,你不能再使用它作为一个过滤器:

<div class="panel-body"> 
     Daytime temperature: {{ filterFn(weatherObject.temp.day) }} 
    </div> 

我想要的过滤器函数返回一个原语(字符串,数字,布尔)。如果它返回一些复杂的(对象,数组),你可能需要缓存返回值以避免无限的摘要循环。


您可以实现滤机:

angular.module(...) 
    .filter('metafilter', ['$filter', function($filter) { 
     return function(input, filterName) { 
      return $filter(filterName)(input); 
     }; 
    }]); 

使用它作为:

<div class="panel-body"> 
     Daytime temperature: {{ weatherObject.temp.day | metafilter:filterTemp }} 
    </div> 

这是一个小提琴展示滤机:https://jsfiddle.net/opL1zfzd/

+0

我知道我可以使用一个函数,但是无论如何,我可以通过我想要的过滤器,还是不可能? –

+0

你可以通过在'compile'函数中操作模板来完成它。你不想这样做。您也可以自己编译包含过滤器名称的HTML片段。你不希望那样(无缘无故太复杂)。我不知道任何其他方式*结构*动态更改模板。另一方面,你可以实现一个元过滤器来完成上面的'filterFn'的功能,但是在过滤器的打包过程中。如果它有用,我会更新这个问题。 –

1

你并不需要在控制器访问它在使用它视图。这是过滤器的重点。如果您真的需要在控制器中使用它,您可以通过要求注入filterTempFilter来请求它。或者您可以注入$ filter提供程序并从中请求您的特定过滤器。

相关问题