1

I'm new to angular.js and still struggling to catch best practices. In this particular case I'm unsure what would be angular way to dynamically add and remove event handlers.

I've created an simplified example that mimic my problem. In this example user can select from one of the items in a list. To select an item, user clicks on button that will display list. Clicking on a list, selection will be changed and list hidden.

But, what I want to do now is enable user to click anywhere on a page to hide list. Using jQuery approach I would add click event handler on body or document that would change view state and hide popup list.

I've created an example on jsfiddle with this approach. My question is: Is this good practice in angular.js? It feels kind of hackish.

Also, please note that I don't want to have a event handler present on document all the time, only when list is displayed.

3
  • It is a bit hackish. You should be using directives to handle any dom manipulation and event listening. Commented Jul 14, 2014 at 13:20
  • put it in a directive so you can keep DOM manipulation out of controller Commented Jul 14, 2014 at 13:20
  • That is a way I thought was right, but after looking through some directive tutorials, examples and documentation I still haven't figured out in what way to implement it. That is why I posted it on stackoverflow. How to create directive that will be added/removed dynamically? Commented Jul 14, 2014 at 13:27

1 Answer 1

1

Using practices described in angular.js guide, I've created directive that should handle the show/hide events.

.directive('toggleListDisplay', function($document) {
    return function(scope, element, attr) {
        var hideList = function (event) {
            scope.listDisplayed = false;
            $document.off('click', hideList);
            scope.$apply();
        };

        element.on('click', function(event) {
            event.stopPropagation();
            scope.listDisplayed = !scope.listDisplayed;
            if (scope.listDisplayed) {
                $document.on('click', hideList);
            } else {
                $document.off('click', hideList);
            }
            scope.$apply();
        });
    };
});

This directive will add click event handler on element, and will start looking for a click on a document untill list is displayed. When it is not displayed anymore, it will stop watching for click event on document.

Working example can be found on jsfiddle.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.