我将此tutorial用于我的角度下拉列表。
当您点击dropdown-list__item或下拉容器周围的任何区域时,现在下拉关闭。
我需要通过克服div.dropdown-display为关闭下拉列表添加代码。
<div class="dropdown-container" ng-class="{ show: listVisible }">
<div class="dropdown-display" ng-click="show();" ng-class="{ clicked: listVisible }">
<span ng-if="!isPlaceholder">{{display}}</span>
<span class="placeholder" ng-if="isPlaceholder">{{placeholder}}</span>
<i class="dropdown__arrow"></i>
</div>
<div class="dropdown-list">
<div>
<div class="dropdown-list__item" ng-repeat="item in list" ng-click="select(item)" ng-class="{ selected: isSelected(item) }">
<span class="dropdown-list__item__text">{{property !== undefined ? item[property] : item}}</span>
</div>
</div>
</div>
和此模板的js代码
app.run(function($rootScope) {
angular.element(document).on("click", function(e) {
$rootScope.$broadcast("documentClicked", angular.element(e.target));
});
});
app.directive("dropdown", function($rootScope) {
return {
restrict: "E",
templateUrl: "templates/dropdown.html",
scope: {
placeholder: "@",
list: "=",
selected: "=",
property: "@"
},
link: function(scope) {
scope.listVisible = false;
scope.isPlaceholder = true;
scope.select = function(item) {
scope.isPlaceholder = false;
scope.selected = item;
};
scope.isSelected = function(item) {
return item[scope.property] === scope.selected[scope.property];
};
scope.show = function() {
scope.listVisible = true;
};
$rootScope.$on("documentClicked", function(inner, target) {
console.log($(target[0]).is(".dropdown-display.clicked") || $(target[0]).parents(".dropdown-display.clicked").length > 0);
if (!$(target[0]).is(".dropdown-display.clicked") && !$(target[0]).parents(".dropdown-display.clicked").length > 0)
scope.$apply(function() {
scope.listVisible = false;
});
});
scope.$watch("selected", function(value) {
scope.isPlaceholder = scope.selected[scope.property] === undefined;
scope.display = scope.selected[scope.property];
});
}
}
});