问题描述
场景
我有一个包含有关他们信息的用户数组,我做了一个 ng-repeat
结合一个自定义指令来生成一个 HTML 用户卡,保持每张卡相对于单个用户的范围,在用户模型在编译模板之前,我需要使用自定义过滤器过滤一个值,因为如果我在模板内部进行过滤,则过滤所需的时间会使工具提示在值准备好之前不显示并且看起来好像有什么东西不工作一样.
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.
到目前为止我的代码
// 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
推荐答案
尝试注入 filterprovider 和运行过滤器.
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);
});
}],
这篇关于AngularJs - 在指令控制器中使用自定义过滤器的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!