首先 - 让我为成为一名角色新手而道歉。
我目前正在开发新的网络应用并试图遵循风格指南(https://github.com/johnpapa/angular-styleguide)
我已经完成了工作,但目前必须在我的每个控制器中声明我的过滤功能。
我希望没有这种重复,并在自己的文件中有一个副本,但如果我这样做并尝试在我的模板中使用它,则无法识别。
我的过滤功能是:
(function() {
'use strict';
angular
.module('lfms')
.filter('includeDeleted', includeDeleted);
includeDeleted.$inject = ['property', 'includeDeleted'];
function includeDeleted(property, includeDeleted) {
if (includeDeleted) {
return function (item) {
return true;
}
} else {
return function (item) {
return !(item[property]);
}
}
}
})();
我尝试按如下方式使用它:
<tr ng-repeat="crew_member_detail in vm.crew_members | filter: vm.includeDeleted('deletedAt', vm.showDeleted) | filter:vm.search | orderBy: predicate:reverse">
如果我在控制器中包含该功能(如下所示),一切正常:
(function() {
'use strict';
angular
.module('lfms')
.controller('CrewController', CrewController);
CrewController.$inject = ['CrewData', '$filter'];
function CrewController(CrewData, $filter) {
var vm = this;
vm.crew_members = CrewData("");
vm.showDeleted = false;
vm.includeDeleted = includeDeleted;
function includeDeleted(property, includeDeleted) {
if (includeDeleted) {
return function (item) {
return true;
}
} else {
return function (item) {
return !(item[property]);
}
}
}
}
})();
我试过删除&#34; vm。&#34;过滤器之前但仍然没有。我认为这是一个范围问题,但似乎无法找到任何指导我找到解决方案的东西。
我感谢您提供任何帮助!
答案 0 :(得分:0)
您可以创建过滤服务 - 请参阅https://github.com/johnpapa/angular-styleguide#services:
(function() {
'use strict';
angular
.module('app')
.service('filterSrv', filterSrv);
function filterSrv() {
this.includeDeleted = function(property, includeDeleted) {
if (includeDeleted) {
return function (item) {
return true;
}
} else {
return function (item) {
return !(item[property]);
}
}
}
// add more filter methods
}
})();
然后在你的控制器中注入你的filterService:
(function() {
'use strict';
angular
.module('lfms')
.controller('CrewController', CrewController);
CrewController.$inject = ['$filter','CrewData', 'filterSrv'];
function CrewController($filter, CrewData, filterSrv) {
var vm = this;
vm.crew_members = CrewData("");
vm.showDeleted = false;
vm.includeDeleted = filterSrv.includeDeleted;
}
})();