[英]AngularJs - Use custom filter inside directive controller
腳本
我有一組用戶包含有關它們的信息,我做一個ng-repeat
結合自定義指令生成HTML用戶卡,保持每張卡的范圍相對於單個用戶,在用戶模型中有一個值我需要在編譯模板之前使用自定義過濾器進行過濾,因為如果我在模板內部進行過濾,則需要過濾的時間使得工具提示在值准備就緒之前不會顯示,看起來好像有些東西不起作用。
我的代碼到目前為止
// 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並運行您的過濾器。
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.