Angularjs click outside event not working in child directive - angularjs

I'm trying to create a dropdown list inside of a button - when clicking the button the dropdown list should open.
I'm trying to get the list hidden with a click outside. The dropdown is actually closing when clicking outside, but it is also closed when clicking on the list - which is not expected.
How do I keep the list open when clicking inside the list?
stopPropagation is not a good solution to me since it corrupts the expected flow of the click event.
Appreciate your help.
http://next.plnkr.co/edit/1HousD8KytGept0o

I don't know why you have created so many directives to handle this task. I have edited 'onClickOutside' directive of your project in order to achieve what you have asked. Please refer to the following example.
app.directive('onClickOutside', ['$document', "$parse", function ($document, $parse) {
return {
restrict: 'A',
link: function (scope, element, attr, controller) {
function isDescendant(parent, child) {
var node = child.parentNode;
while (node != null) {
if (node == parent) {
return true;
}
node = node.parentNode;
}
return false;
}
var anyOtherClickFunction = $parse(attr["onClickOutside"]);
var documentClickHandler = function (event) {
var isChild = element[0] && isDescendant(element[0], event.target);
var showList = true;
if (!isChild) {
if (element[0] == event.target) showList = true;
else showList = false;
}
scope.$apply(function () {
scope.showList = showList;
});
};
$document.on("contextmenu", documentClickHandler);
$document.on("click", documentClickHandler);
scope.$on("$destroy", function () {
$document.off("contextmenu", documentClickHandler);
$document.off("click", documentClickHandler);
});
}
};
}]);

Related

Ionic focus gets removed from input-emelent

I'd like to build a multiple input area for e-mail addresses. I started building a prototype with pure angularjs, that worked:
angular-fiddle
The input field gets displayed if one of the elements get clicked:
$scope.focus = true;
This is the variable I need to show the input field. If focus is false, the input field is not displayed. Or if the area receives a click-event.
In order to set the focus on the input, in order to start typing directly, I use:
element[0].focus();
That works unless I use the ionic-framework. As soon as the input got the focus, it's taken away:
ionic-fiddle
Why is the focus taken away by using ionic?
autofocus seems to be the problem. it will instantly fire a blur event and cause to hide the input field again. Try to manually to focus on the input field after the input is visible (with $timeout). See http://jsfiddle.net/awqtsLpy/. I moved the edit function to the directive.link section to get access to the element.
app.directive('emailRecipients', function ($timeout) {
return {
restrict: 'E',
controller: function ($scope) {
$scope.focus = false;
$scope.addressees = [];
var i = 10;
while (i) {
$scope.addressees.push({
"name": i
});
i--;
}
},
link: function ($scope, element) {
$scope.click = function () {
$scope.focus = !$scope.focus;
$scope.value = null;
}
$scope.deleteFromInput = function ($event) {
$event.stopPropagation();
}
$scope.edit = function ($event, addressee) {
$event.stopPropagation();
$scope.value = addressee;
addressee.editable = true;
$scope.focus = true;
$timeout(function () {
element.find('input').focus();
});
}
}
}
});

Registering beforeunload event in directive

I have the following directive which I use to warn the user if they attempt to close the window or navigate away without saving their changes:
app.directive('dirtyTracking', ['$window', function ($window) {
return {
restrict: 'A',
link: function ($scope, $element, $attrs) {
function isDirty() {
var formObj = getProperty($scope, $element.attr('name'));
return formObj && formObj.$pristine === false;
}
//So we can read string keys such as foo.bar and correctly
//traverse the javascript object
function getProperty(obj, prop) {
var parts = prop.split('.'),
last = parts.pop(),
l = parts.length,
i = 1,
current = parts[0];
while ((obj = obj[current]) && i < l) {
current = parts[i];
i++;
}
if (obj) {
return obj[last];
}
}
function areYouSurePrompt() {
if (isDirty()) {
return 'You have unsaved changes.';
}
}
window.onbeforeunload = areYouSurePrompt;
//window.addEventListener('beforeunload', areYouSurePrompt);
$element.bind("$destroy", function () {
window.removeEventListener('beforeunload', areYouSurePrompt);
});
$scope.$on('$locationChangeStart', function (event) {
var prompt = areYouSurePrompt();
if (!event.defaultPrevented && prompt && !confirm(prompt)) {
event.preventDefault();
}
});
}
};
}]);
As it currently stands, this works, but as you can see, I have to explictly set the window.onbeforeunload property. The problem with this approach is that if I have other directives that want to do things on the save event, they will clobber each other.
When I attempted to use window.addEventListener or $window.addEventListener the event does not seem to work as expected.
Stepping through the debugger, the code does enter the areYouSurePrompt function and does return the string, however I am not prompted with a confirm dialog before the window closes.
I am aware I can use the approach where I save the current value of window.onbeforeunload but I'd rather figure out why using the addEventListner isn't working as expected.

AngularJs: Run function when any element in section is blurred

I've created the following directive:
.directive('onSectionBlur', function ($parse) {
return {
restrict: 'A',
controller: function ($scope, $element, $attrs) {
$element.focusout(function (event) {
if (!jQuery.contains($element[0], event.relatedTarget)) {
$scope.$apply($parse($attrs.onSectionBlur)($scope));
}
});
}
};
})
My goal here is if a user tabs out of a section of a form (or clicks elsewhere), I want to display a read-only version of that data: http://jsfiddle.net/uZBXw/3/
So this works from what I can tell, but I feel like I was just mashing buttons on this line:
$scope.$apply($parse($attrs.onSectionBlur)($scope));
Is this the correct way to run code and wire it into the angular lifecycle?
I think you should use an isolated scope with an attribute marked with &. This will give you access to a function that will run on the parent scope and is the exact use case of what you're trying to do.
app.directive('onSectionBlur', function () {
return {
restrict: 'A',
scope: {
'notify': '&onSectionBlur' // reuse the directive name for easier handling
},
link: function (scope, element) {
element.on('focusout', function (evt) {
if (!angular.element.contains(element[0], evt.relatedTarget)) {
scope.$apply(scope.notify); // let $apply call the notify-callback
}
});
}
};
});
demo: http://jsbin.com/diwetaje/1/
from the Developer Guide:
Best Practice: use &attr in the scope option when you want your directive to expose an API for binding to behaviors.
I was having issues with clicking on various items in the section (i.e. checkbox labels), so if anyone else runs across this issue I've added a potential enhancement to Yoshi's version:
.directive('onSectionBlur', function ($document) {
return {
restrict: 'A',
scope: {
'notify': '&onSectionBlur'
},
link: function (scope, element) {
var hasFocus = false;
element.on('focusin', function (evt) {
hasFocus = true;
});
$document.on('click focusin', function (evt) {
if (hasFocus && !angular.element.contains(element[0], evt.target)) {
hasFocus = false;
scope.$apply(scope.notify);
}
});
}
};
});
EDIT: Here's the butchered up version I ended up with, that takes into account buttons that weren't clickable (if they were outside the section and below it) as well as not firing the event if the user has a modal window open:
link: function (scope, element) {
var hasFocus = false;
var lostFocus = function () {
hasFocus = false;
scope.$apply(scope.notify);
};
element.on('focusin', function (evt) {
hasFocus = true;
});
element.on('keydown', function (evt) {
if (hasFocus && evt.keyCode == 9) {
//Using timeout to give the browser time to process what it should have been doing (i.e. focusing next item)
if (evt.shiftKey && element.find(':focusable:first').is(evt.target)) {
$timeout(lostFocus);
} else if (element.find(':focusable:last').is(evt.target)) {
$timeout(lostFocus);
}
}
});
var docHandler = function (evt) {
//If the click came from inside of a modal window, ignore it
if (angular.element(evt.target).closest('.modal').length == 0) {
if (hasFocus && !angular.element.contains(element[0], evt.target)) {
lostFocus();
}
}
};
$document.on('click', docHandler);
scope.$on('$destroy', function () {
$document.off('click', docHandler);
});
}

AngularJS: Preventing 'mouseenter' event triggering on child elements

I'm playing right now with the AngularJS framework and I stumbled upon a problem. I made a directive which is called 'enter'. It triggers functions on mouseenter and mouseleave. I applied it as an attribute to the table row elements. It is now triggered for every child element (all the columns and etc), but it should be only triggered, when you go with your mouse over the table row.
This is how my directive looks like:
myapp.directive('enter', function(){
return {
restrict: 'A', // link to attribute... default is A
link: function (scope, element){
element.bind('mouseenter',function() {
console.log('MOUSE ENTER: ' + scope.movie.title);
});
element.bind('mouseleave',function() {
console.log('LEAVE');
});
}
}
});
Here is an example: http://jsfiddle.net/dJGfd/1/
You have to open the Javascript console to see the log messages.
What is the best way to achieve the functionality that I want in AngularJS? I prefer to not use jQuery if there is a reasonable AngularJS solution.
You can try this:
myapp.directive('enter', function () {
return {
restrict: 'A',
controller: function ($scope, $timeout) {
// do we have started timeout
var timeoutStarted = false;
// pending value of mouse state
var pendingMouseState = false;
$scope.changeMouseState = function (newMouseState) {
// if pending value equals to new value then do nothing
if (pendingMouseState == newMouseState) {
return;
}
// otherwise store new value
pendingMouseState = newMouseState;
// and start timeout
startTimer();
};
function startTimer() {
// if timeout started then do nothing
if (timeoutStarted) {
return;
}
// start timeout 10 ms
$timeout(function () {
// reset value of timeoutStarted flag
timeoutStarted = false;
// apply new value
$scope.mouseOver = pendingMouseState;
}, 10, true);
}
},
link: function (scope, element) {
//**********************************************
// bind to "mouseenter" and "mouseleave" events
//**********************************************
element.bind('mouseover', function (event) {
scope.changeMouseState(true);
});
element.bind('mouseleave', function (event) {
scope.changeMouseState(false);
});
//**********************************************
// watch value of "mouseOver" variable
// or you create bindings in markup
//**********************************************
scope.$watch("mouseOver", function (value) {
console.log(value);
});
}
}
});
Same thing at http://jsfiddle.net/22WgG/
Also instead
element.bind("mouseenter", ...);
and
element.bind("mouseleave", ...);
you can specify
<tr enter ng-mouseenter="changeMouseState(true)" ng-mouseleave="changeMouseState(false)">...</tr>
See http://jsfiddle.net/hwnW3/

AngularJS dropdown directive hide when clicking outside

I'm trying to create a multiselect dropdown list with checkbox and filter option. I'm trying to get the list hidden with I click outside but could not figure it out how. Appreciate your help.
http://plnkr.co/edit/tw0hLz68O8ueWj7uZ78c
Watch out, your solution (the Plunker provided in the question) doesn't close the popups of other boxes when opening a second popup (on a page with multiple selects).
By clicking on a box to open a new popup the click event will always be stopped. The event will never reach any other opened popup (to close them).
I solved this by removing the event.stopPropagation(); line and matching all child elements of the popup.
The popup will only be closed, if the events element doesn't match any child elements of the popup.
I changed the directive code to the following:
select.html (directive code)
link: function(scope, element, attr){
scope.isPopupVisible = false;
scope.toggleSelect = function(){
scope.isPopupVisible = !scope.isPopupVisible;
}
$(document).bind('click', function(event){
var isClickedElementChildOfPopup = element
.find(event.target)
.length > 0;
if (isClickedElementChildOfPopup)
return;
scope.$apply(function(){
scope.isPopupVisible = false;
});
});
}
I forked your plunker and applied the changes:
Plunker: Hide popup div on click outside
Screenshot:
This is an old post but in case this helps anyone here is a working example of click outside that doesn't rely on anything but angular.
module('clickOutside', []).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);
});
}
});
}
}
});
OK I had to call $apply() as the event is happening outside angular world (as per doc).
element.bind('click', function(event) {
event.stopPropagation();
});
$document.bind('click', function(){
scope.isVisible = false;
scope.$apply();
});
I realized it by listening for a global click event like so:
.directive('globalEvents', ['News', function(News) {
// Used for global events
return function(scope, element) {
// Listens for a mouse click
// Need to close drop down menus
element.bind('click', function(e) {
News.setClick(e.target);
});
}
}])
The event itself is then broadcasted via a News service
angular.factory('News', ['$rootScope', function($rootScope) {
var news = {};
news.setClick = function( target ) {
this.clickTarget = target;
$rootScope.$broadcast('click');
};
}]);
You can then listen for the broadcast anywhere you need to. Here is an example directive:
.directive('dropdown', ['News', function(News) {
// Drop down menu für the logo button
return {
restrict: 'E',
scope: {},
link: function(scope, element) {
var opened = true;
// Toggles the visibility of the drop down menu
scope.toggle = function() {
element.removeClass(opened ? 'closed' : 'opened');
element.addClass(opened ? 'opened' : 'closed');
};
// Listens for the global click event broad-casted by the News service
scope.$on('click', function() {
if (element.find(News.clickTarget.tagName)[0] !== News.clickTarget) {
scope.toggle(false);
}
});
// Init
scope.toggle();
}
}
}])
I hope it helps!
I was not totally satisfied with the answers provided so I made my own. Improvements:
More defensive updating of the scope. Will check to see if a apply/digest is already in progress
div will also close when the user presses the escape key
window events are unbound when the div is closed (prevents leaks)
window events are unbound when the scope is destroyed (prevents leaks)
function link(scope, $element, attributes, $window) {
var el = $element[0],
$$window = angular.element($window);
function onClick(event) {
console.log('window clicked');
// might need to polyfill node.contains
if (el.contains(event.target)) {
console.log('click inside element');
return;
}
scope.isActive = !scope.isActive;
if (!scope.$$phase) {
scope.$apply();
}
}
function onKeyUp(event) {
if (event.keyCode !== 27) {
return;
}
console.log('escape pressed');
scope.isActive = false;
if (!scope.$$phase) {
scope.$apply();
}
}
function bindCloseHandler() {
console.log('binding window click event');
$$window.on('click', onClick);
$$window.on('keyup', onKeyUp);
}
function unbindCloseHandler() {
console.log('unbinding window click event');
$$window.off('click', onClick);
$$window.off('keyup', onKeyUp);
}
scope.$watch('isActive', function(newValue, oldValue) {
if (newValue) {
bindCloseHandler();
} else {
unbindCloseHandler();
}
});
// prevent leaks - destroy handlers when scope is destroyed
scope.$on('$destroy', function() {
unbindCloseHandler();
});
}
I get $window directly into the link function. However, you do not need to do this exactly to get $window.
function directive($window) {
return {
restrict: 'AE',
link: function(scope, $element, attributes) {
link.call(null, scope, $element, attributes, $window);
}
};
}
There is a cool directive called angular-click-outside. You can use it in your project. It is super simple to use:
https://github.com/IamAdamJowett/angular-click-outside
The answer Danny F posted is awesome and nearly complete, but Thịnh's comment is correct, so here is my modified directive to remove the listeners on the $destroy event of the directive:
const ClickModule = angular
.module('clickOutside', [])
.directive('clickOutside', ['$document', function ($document) {
return {
restrict: 'A',
scope: {
clickOutside: '&'
},
link: function (scope, el, attr) {
const handler = function (e) {
if (el !== e.target && !el[0].contains(e.target)) {
scope.$apply(function () {
console.log("hiiii");
// whatever expression you assign to the click-outside attribute gets executed here
// good for closing dropdowns etc
scope.$eval(scope.clickOutside);
});
}
}
$document.on('click', handler);
scope.$on('$destroy', function() {
$document.off('click', handler);
});
}
}
}]);
If you put a log in the handler method, you will still see it fire when an element has been removed from the DOM. Adding my small change is enough to remove it. Not trying to steal anyone's thunder, but this is a fix to an elegant solution.
Use angular-click-outside
Installation:
bower install angular-click-outside --save
npm install #iamadamjowett/angular-click-outside
yarn add #iamadamjowett/angular-click-outside
Usage:
angular.module('myApp', ['angular-click-outside'])
//in your html
<div class="menu" click-outside="closeThis">
...
</div>
//And then in your controller
$scope.closeThis = function () {
console.log('closing');
}
I found some issues with the implementation in https://github.com/IamAdamJowett/angular-click-outside
If for example the element clicked on is removed from the DOM, the directive above will trigger the logic.
That didn't work for me, since I had some logic in a modal that, after click, removed the element with a ng-if.
I rewrote his implementation. Not battle tested, but seems to be working better (at least in my scenario)
angular
.module('sbs.directives')
.directive('clickOutside', ['$document', '$parse', '$timeout', clickOutside]);
const MAX_RECURSIONS = 400;
function clickOutside($document, $parse, $timeout) {
return {
restrict: 'A',
link: function ($scope, elem, attr) {
// postpone linking to next digest to allow for unique id generation
$timeout(() => {
function runLogicIfClickedElementIsOutside(e) {
// check if our element already hidden and abort if so
if (angular.element(elem).hasClass('ng-hide')) {
return;
}
// if there is no click target, no point going on
if (!e || !e.target) {
return;
}
let clickedElementIsOutsideDirectiveRoot = false;
let hasParent = true;
let recursions = 0;
let compareNode = elem[0].parentNode;
while (
!clickedElementIsOutsideDirectiveRoot &&
hasParent &&
recursions < MAX_RECURSIONS
) {
if (e.target === compareNode) {
clickedElementIsOutsideDirectiveRoot = true;
}
compareNode = compareNode.parentNode;
hasParent = Boolean(compareNode);
recursions++; // just in case to avoid eternal loop
}
if (clickedElementIsOutsideDirectiveRoot) {
$timeout(function () {
const fn = $parse(attr['clickOutside']);
fn($scope, { event: e });
});
}
}
// if the devices has a touchscreen, listen for this event
if (_hasTouch()) {
$document.on('touchstart', function () {
setTimeout(runLogicIfClickedElementIsOutside);
});
}
// still listen for the click event even if there is touch to cater for touchscreen laptops
$document.on('click', runLogicIfClickedElementIsOutside);
// when the scope is destroyed, clean up the documents event handlers as we don't want it hanging around
$scope.$on('$destroy', function () {
if (_hasTouch()) {
$document.off('touchstart', runLogicIfClickedElementIsOutside);
}
$document.off('click', runLogicIfClickedElementIsOutside);
});
});
},
};
}
function _hasTouch() {
// works on most browsers, IE10/11 and Surface
return 'ontouchstart' in window || navigator.maxTouchPoints;
}

Resources