dugokontov
dugokontov

Reputation: 4612

Dynamically add and remove events in angular.js

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.

Upvotes: 1

Views: 1871

Answers (1)

dugokontov
dugokontov

Reputation: 4612

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.

Upvotes: 1

Related Questions