7

Scenario
I have an array of users containing information about them, I do an ng-repeat combined with a custom directive that generates an HTML user card, keeping the scope of each card relative to the individual user, inside the user model there is a value that I need to filter with a custom filter before the template gets compiled, because if I do it inside the template the time it takes to be filtered makes the tooltip not to show until the value is ready and that looks as if something is not working.

My code so far

// userCard directive
angular.module('userCard', []).directive('UserCard', function() {
  return {
    restrict: 'EA',
    templateUrl: 'userCard.tpl.html',
    scope: {
        user: '='
    },
    controller: ['$scope', 'fromNowFilter', function($scope, fromNowFilter) {

        angular.forEach($scope.user.reminders, function(reminder) {
            reminder.last_sent = reminder.last_sent === null ? 'No reminder has been sent!' : fromNowFilter(reminder.last_sent);
        });
    }],
    link: function(scope, element) {
        // Add the base class to the user card element
        element.addClass('user-card');
    }
  };
});


// fromNow custom filter
angular.module('userCard').filter('fromNow', function() {
  return function(date) {
    return moment(date).fromNow();
  };
});


// The error I keep getting
Unknown provider: fromNowFilterProvider <- fromNowFilter

1 Answer 1

21

Try inject filterprovider and run your filter.

controller: ['$scope', '$filter', function($scope, $filter) {
       var fromNowFilter = $filter('fromNow');
        angular.forEach($scope.user.reminders, function(reminder) {
            reminder.last_sent = reminder.last_sent === null ? 'No reminder has been sent!' : fromNowFilter(reminder.last_sent);
        });
    }],
Sign up to request clarification or add additional context in comments.

9 Comments

Just tried that but still getting the same error, I am trying to follow the Angular docs, what I understand is that you need to postfix your filter name with Filter to inject it.
@CupOfJoe Yeah that should have worked as well.. Are you sure you have loaded the scipt for the filter in your app?
Yes, I tested it inside the template and it works, but cant' get it to inject inside the directives controller.
@CupOfJoe It works for me.. See this demo. plnkr.co/edit/0jhiqM?p=preview Which version of angular you are using?
it should be like var fromNowFilter = $filter('fromNow'); not var fromNowFilter = $filter('fromNowFilter '); we don't want to concatenate filter
|

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.