Skip to content

Instantly share code, notes, and snippets.

@rintaun
Last active December 17, 2015 15:08
Show Gist options
  • Save rintaun/5629040 to your computer and use it in GitHub Desktop.
Save rintaun/5629040 to your computer and use it in GitHub Desktop.

So, I have noticed a pattern that has appeared in how I develop directives, and I'm wondering if there isn't a better way to accomplish the same thing. Specifically, I find that in a directive with its own scope (either isolated or inherited), it is sometimes useful to add utility methods to the parent scope. For example:

directive('hello', function() {
    return {
        restrict: 'A',
        scope: {},
        link: function(scope, elem, attrs) {
            scope.$parent.alert = function() {
                var who = attrs.hello || 'World'
                alert('Hello ' + who + '!');
            }
        }
    };
});

The utility of this is that instead of the directive dictating when a particular piece code is called (e.g. adding a click event listener to the element), it makes that functionality available to the parent scope and allows it to decide when to call it.

One example where this has appeared in my directives is in a tabset directive, which adds a tabset object with the functions prev(), next(), and goTo(index). This enables switching between tabs programmatically in the controller, or from other directives in the parent scope (e.g. ng-click on sibling element).

I've considered using a service, but it seems that the singleton nature of services doesn't fit well with the needs (e.g. functions being bound to a particular scope) in this case.

So the question remains -- is there a better way to accomplish the same thing? Or is this just fine?

@CMCDragonkai
Copy link

Did you try using the & isolate expression binding? The = binding could also work by binding your functions to an object that the parent supplies. This is basically the directive exposing a public API.

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