ps0604
ps0604

Reputation: 1081

Changing directive function dynamically

Given the following directive:

app.directive("myDirective", function() {
          return {
            restrict: "AE",        
            scope: {              
                myFunction: '&'
            },

            templateUrl: "some_template.html",
            link: function (scope, element) {
            }
         }
   });

I declare it as

<my-directive my-function="function1()"></my-directive>

But my problem is that in the controller I need to call function1 or function2 depending on a condition. Is there a way to dynamically change the function in my-function attribute?

Upvotes: 0

Views: 31

Answers (1)

Samir Aguiar
Samir Aguiar

Reputation: 2559

Yes, just set it to some variable instead that references one function or the other:

<my-directive my-function="functionToCall()"></my-directive>

This functionToCall can be changed dynamically as you need:

<button type="button" ng-click="functionToCall = function1">Switch to function 1</button>
<button type="button" ng-click="functionToCall = function2">Switch to function 2</button>

Check this Plunker for a working example.

Upvotes: 1

Related Questions