Ниже приведен пример фрагмента с использованием директивы и специального фильтра с необязательным состоянием (по умолчанию disabled
)
Шаблон директивы встроен, поскольку я не могу добавить внешний файл в фрагмент StackOverflow.
(function () {
'use strict';
angular.module('app', []);
angular
.module('app')
.directive('items', function () {
return {
restrict: 'EAC',
scope: {},
template: '<ul><li ng-repeat="item in vm.items|excludedItemsFilter:\'disabled\'">{{item.label}}</li></ul>',
link: link,
controller: controller,
controllerAs: 'vm'
};
function link(scope, element, attrs) {
scope.$on('$destroy', function () {
// destroy events binded to $rootScope,
// cancel $interval and $timeout timers
});
}
function controller($scope) {
var vm = this;
vm.items = [
{label: "Item 1", status: "enabled"},
{label: "Item 2", status: "enabled"},
{label: "Item 3", status: "disabled"},
{label: "Item 4", status: "enabled"},
{label: "Item 5", status: "disabled"}
];
}
});
angular
.module('app')
.filter('excludedItemsFilter', function () {
return function (items, excludedStatus) {
excludedStatus = excludedStatus || 'disabled'; // default value
return items.filter(function (item) {
return item
&& item.status !== excludedStatus;
});
}
});
})();
<!DOCTYPE html>
<html lang="en" ng-app="app">
<head>
<meta charset="utf-8" />
<script src="https://cdnjs.cloudflare.com/ajax/libs/angular.js/1.6.1/angular.min.js"></script>
<script src="module.js"></script>
</head>
<body>
<div items></div>
</body>
</html>
Вы также можете удалить специальный фильтр и фильтровать элементы в директиве, например:
angular.module("app").directive("items", function () {
return {
restrict: "EAC",
scope: {},
template: '<ul><li ng-repeat="item in vm.items">{{item.label}}</li></ul>',
link: link,
controller: controller,
controllerAs: "vm",
};
function link(scope, element, attrs) {
scope.$on("$destroy", function () {
// destroy events binded to $rootScope,
// cancel $interval and $timeout timers
});
}
function controller($scope) {
var vm = this;
vm.items = [
{ label: "Item 1", status: "enabled" },
{ label: "Item 2", status: "enabled" },
{ label: "Item 3", status: "disabled" },
{ label: "Item 4", status: "enabled" },
{ label: "Item 5", status: "disabled" },
].filter(function (item) {
return item && item.status !== "disabled";
});
}
});