Take the 2-minute tour ×
Stack Overflow is a question and answer site for professional and enthusiast programmers. It's 100% free, no registration required.

So I have a navigation that I want to have a dropdrown menu with sub-menu functionality on it. I tried ng-show for showing and hiding the menus but then I would have to go back and click on item again to hide it. I want to be able to click to show, then click anywhere else to hide it.

trying to use ng-click but not sure where I should put my custom function that I want to retrieve regardless of the controller being used.

Would I put something like this in a directive? The function is not calling html or getting any content like a factory is generally for, it simply shows and hides content on different click events.

share|improve this question
    
You should realy show us some code of what you have tried –  Chancho Apr 28 '14 at 20:55

2 Answers 2

There are probably more complicated ways of doing this that might be more elegant, but I've found this to do the trick in the past. Assumes you're loading jQuery before Angular so $ is full jQuery. If you're finding yourself doing this with many different DOM elements though, it might be more effective to break this out into a factory that allows many objects to register themselves in this way with just one binding to body.

app.directive('clickOffHide',function() {
    return {
        ...
        link: function(.., elem, ..) {
            $('body').click(function(evt) {
                var $elem = $(elem);
                var $target = $(evt.target);
                if($elem.is($target) || $elem.has($target).length > 0) return;
                $elem.hide();
            });
        }
    }
});
share|improve this answer
    
Thanks for the reply. I was thinking more this could be as simple as: ngclick="$('.drop-down-menu').hide()". that doesnt work, but how could i do this with angular? –  user2174484 Apr 28 '14 at 23:08
    
I'm not sure what you're trying to do that isn't captured by this directive. Are you wondering how to get that ng-click directive on the body calling a function in a global controller? I would highly suggest the directive route over that as it's much more modular and reusable. Maybe I'm misunderstanding your question. –  Patrick Apr 29 '14 at 0:24

You could try using ng-blur on the drop-down element.

<div ng-class="dropDown" ng-blur="functionToHideElement" tabindex="100">Products</div>

A div element can accept a blur event if it has a specified tabindex.

This way you can use a baked in Angular directive rather than creating your own.

share|improve this answer

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

Not the answer you're looking for? Browse other questions tagged or ask your own question.