[英]Click outside the div get hide in Angular js
當我們在 div 外部或窗口中單擊時,xyz 應該被隱藏
var app = angular.module('myApp', []);
app.controller('myCtrl', function($scope) {
$scope.showDropdown = false;
$scope.helloClick = function(){
if($scope.showDropdown == true){
$scope.showDropdown = false;
}
else{
$scope.showDropdown = true;
}
}
});
這是我的 jsfiddler 鏈接https://jsfiddle.net/8ftrnenw/
這是您所需的解決方案,
custom directive
click-outside
屬性,並檢查是否在添加了該指令的元素上單擊。 element
之外,那么它將隱藏該div
var app = angular.module('myApp', []); app.controller('myCtrl', function($scope) { $scope.showDropdown = false; $scope.hide = function(){ $scope.showDropdown = false; } $scope.helloClick = function(){ $scope.showDropdown = !$scope.showDropdown; } } }); app.directive('clickOutside', function ($document) { return { restrict: 'A', scope: { clickOutside: '&' }, link: function (scope, el, attr) { $document.on('click', function (e) { if (el !== e.target && !el[0].contains(e.target)) { scope.$apply(function () { scope.$eval(scope.clickOutside); }); } }); } } });
.xyz{ border:1px solid red; width:200px; height:20px; }
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script> <div ng-app="myApp" ng-controller="myCtrl"> <div click-outside="hide()"> <div class="hello" ng-click ="helloClick()">hello</div> <div class="xyz" ng-if="showDropdown">xyz</div> </div> </div>
請運行上面的代碼段
附:指令說明:
el !== e.target && !el[0].contains(e.target)
e是您單擊的元素,而el是您在其上添加指令的元素。 因此,它將檢查您單擊的元素是否為該指令。 如果不是,那么它將隱藏所需的div
scope.$eval(scope.clickOutside);
這將評估屬性並調用我們在click-outside="hide()"
提供的函數
感謝@Sravan 的回復。 我添加了一項改進,僅在顯示目標組件時才啟動此事件。
app.directive('clickOutside', function ($document) {
return {
restrict: 'A',
scope: {
clickOutside: '&',
launchEvent: '='
},
link: function (scope, el, attr) {
var launched = false;
scope.$watch('launchEvent', function (newVal) {
if (newVal && !launched) {
launched = true;
$document.on('click', function (e) {
if (el !== e.target && !el[0].contains(e.target)) {
scope.$apply(function () {
scope.$eval(scope.clickOutside);
});
}
});
} else {
launched = false;
$document.off('click');
}
});
}
}
});
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.