Javascript ProgrammingTips

Execute a function within a Directive from outside in AngularJS

We were working on two problem statements at different points in time of a project and we interestingly found similar solution for both.

Problem A: We have a form, one of the input fields  (defined as a directive) has a clear button. This clears the text in the input field, the data in the ng-model as well as the data held in the variable that gets submitted finally via the form. Now, we have a universal clear button that also needs to clear all the 3 data points.

Problem B: We have a section that has been defined as a directive which can be expanded/collapsed using a toggle button. The expand/collapse is handled by the directive. The initial state of the directive, whether it should be expanded or collapsed, is actually dependent on a value obtained from an API call.

In both cases the common thing that one can notice is that there is an external trigger that needs to be passed on into the directive. In Angular 1.4 there is no direct way to do this. Directives do support two way binding, and passing initial values. But neither would solve the exact requirement in both problems.

The solution that we came up with was passing a control object to the directive. The controller defined a control object, a key of which will be pointing to a function. This object was passed on to the directive, and directive initialised the control object’s key (control object which is two-way bound) with a function that gives access to the variables/functions inside the directive. Being two-way bound, this function is now available in the controller. This can be passed on to anywhere (factory, as it was in case of solution for problem B) or used locally.

Sample code:


Leave a Reply

Your email address will not be published. Required fields are marked *