Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

AngularJs - Use custom filter inside directive controller

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
like image 269
CupOfJoe Avatar asked Aug 29 '14 01:08

CupOfJoe


People also ask

How do you use a filter on a controller?

There is $filter service that is used in our AngularJS controller. In AngularJS, you can also inject the $filter service within the controller and can use it with the following syntax for the filter. Syntax: $filter("filter")(array, expression, compare, propertyKey) function myCtrl($scope, $filter) { $scope.

What is the true way to apply multiple filters in AngularJS?

Answer: A is the correct option. The syntax of applying multiple filters in AngularJS can be written as: {{ expression | filter1 | filter2 | ... }}

What is the correct way to apply a filter in angular?

Filters can be added to expressions by using the pipe character | , followed by a filter.


1 Answers

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);
        });
    }],
like image 93
PSL Avatar answered Sep 22 '22 23:09

PSL