gpt4 book ai didi

angularjs - 如何在angularjs中检测范围之外的点击

转载 作者:行者123 更新时间:2023-12-05 01:08:22 25 4
gpt4 key购买 nike

我有一个 Angular Controller ,只要用户在 Controller 范围之外单击,它就需要重置。我该怎么做呢?

示例 html:

<div id='parent'>
<div id='1' ng-controller="ctrl1">
<!--other things-->
</div>

<div id='2' ng-controller="ctrl2">
<!--other things-->
</div>
</div>
<div id="parent2">
<!--other things-->
</div>

如果在 ctr2 之外发生单击,我希望能够重置 ctrl2当点击发生在 div2 之外时

ctr2 内部定义了一个重置​​函数

最佳答案

如果您希望在同级 div 中发生单击时重置,那么 Controller 共享 $scope 的事实应该使这相当简单。如果您想在页面上其他任何地方发生点击时重置 div,那么您应该将“重置”div 设置为指令,绑定(bind) $window点击处理程序的对象:

app.directive('reset', function($window){
return {
template: '<div ng-class="{red: directiveToggler}">I\'m in 2' +
' - click me to turn red, click anywhere else to turn me normal'+
'</div>',
controller: function($scope){
$scope.directiveToggler = true;
},
link: function(scope, element){

var w = angular.element($window);
w.bind('click', function(e){

if (e.target != element[0].children[0]){
scope.directiveToggler = false;
scope.$apply();

} else {
scope.directiveToggler = true;
scope.$apply()
}
})
}
}
})

请注意,处理类/样式更改的方法可能比我设置的更好,但问题是关于点击事件;)。

Here's a plunk to demo

关于angularjs - 如何在angularjs中检测范围之外的点击,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17228622/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com