Skip to content

Instantly share code, notes, and snippets.

@zachlysobey
Last active October 28, 2015 17:49
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save zachlysobey/03ce5a1451ec9b760f4a to your computer and use it in GitHub Desktop.
Save zachlysobey/03ce5a1451ec9b760f4a to your computer and use it in GitHub Desktop.

Whats the best, most idiomatic way to make a self-closable directive?

Pass in ng-if?

<toggleBox ng-if="someCondition"></toggleBox>
angular.module('myModule').directive('toggleBox', function() {
    return {
        bindToController: true,
        controller: function() { this.close = function() { this.ngIf = false; }; },
        controllerAs: 'box',
        scope: { ngIf: '=' },
        template: '<div>box <a on-click="box.close()">x</a> </div>'
    };
});

Passing in a function

<toggleBox ng-if="someCondition" on-close="toggleSomeCondition()"></toggleBox>
angular.module('myModule').directive('toggleBox', function() {
    return {
        bindToController: true,
        controller: angular.noop,
        controllerAs: 'box',
        scope: { onClose: '&' },
        template: '<div>box <a on-click="box.onClose()">x</a> </div>'
    };
});

Something Else I didn't think of?

@jaesung2061
Copy link

<toggle-box></toggle-box>, problem solved.

@zachlysobey
Copy link
Author

@jaesung2061, I think you mis-interpreted my question lol. Perhaps using the "self-closing" html element in my example was confusing, I'll change that, but in the title, I meant self-closing as in reference to a directive having a control inside of it which removes itself from the dom via an ng-if on the element

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment