Dynamically add directives in AngularJS (while ditching jQuery)

Let’s say you want to add a button that adds more buttons (or any other interactive element) that do something when you click them.

There is a few ways to achieve this, but most of the solutions I found either didn’t work (probably due to using an older AngularJS version), seemed unnecessarily complicated or relied on using jQuery.

Here is what I came up with (for Angular 1.2.9).

To see a working example with the full code, visit this page. I’m going to walk you through it here.

If jQuery is available, angular.element is an alias for the jQuery function. If jQuery is not available, angular.element delegates to Angular’s built-in subset of jQuery, called “jQuery lite” or “jqLite.”

To use jqLite, you will have to wrap the native JavaScript methods like document.getElementById or document.querySelectorAll with theangular.element function. This may take more space, but you can easily create your own jQuery-style selector function, something like this: