Rectangle 27 0

angularjs Access to custom filter from an Angular directive with isolate scope?

angular.module('directives',['services']).directive('linkBox', ['toDate',function(toDate){

Adam Thomas is correct about that, but it is a common scenario to depend on custom directives, services, and filters in other custom items. You want to make things explicit in your DI assertions. This will cause things to break at the injection level instead of when using the custom directive in this case.

Erstad - The code example listed in this answer will not work as typed. See my post for the reason.

Good call. Thanks for correcting it.

This is because the filter is available to the 'exampleApp' module since it is a dependency.

With this you can be clear about what you need to use the directive and will not be easily missed. This may require you to tweak how you declare 'toDate'.

Rectangle 27 0

angularjs Access to custom filter from an Angular directive with isolate scope?


  $scope.dateVal = 20131010;

  function func(ymd){
    ymd = ymd + "";
    var y = ymd.substring(0,4);
    var m = ymd.substring(4,6);
    var d = ymd.substring(6);
    return (+m) + "/" + (+d) + "/" + y;
  return func;

angular.module('directives',['services']).directive('linkBox', ['toDateFilter', function(toDate){
  var dir = {
    template:'<p>Filtered value: {{isolateVar | toDate}}</p>',
    link: function lfn(scope, instance, attr){
      var a = angular.element(instance); 
    } //end link function
  }; //end dir object
  return dir;

I dig it. Give him the answer!

The following code works:

This is because the directive is a child of the root scope created by the exampleApp module. The services, controllers, and directives modules are injected into exampleApp giving prototypical inheritance up the tree from child to root scope. It is dangerous to rely on the toDate filter being accessible to the linkBox directive in case at some point in the future the root scope created by exampleApp were to exclude the services module.

What Erstad Stephen wrote in his answer is partially correct, but his example won't work as it is typed since the $injector requires filter names to have a suffix of Filter. As is detailed in the $filterProvider docs.