简体   繁体   English

AngularJs - 在指令控制器中使用自定义过滤器

[英]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. 我有一组用户包含有关它们的信息,我做一个ng-repeat结合自定义指令生成HTML用户卡,保持每张卡的范围相对于单个用户,在用户模型中有一个值我需要在编译模板之前使用自定义过滤器进行过滤,因为如果我在模板内部进行过滤,则需要过滤的时间使得工具提示在值准备就绪之前不会显示,看起来好像有些东西不起作用。

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

Try inject filterprovider and run your filter. 尝试注入filterprovider并运行您的过滤器。

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);
        });
    }],

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM