Ovidiu Buligan
Ovidiu Buligan

Reputation: 2802

Angular js directive dynamic template binding

I have a template which looks like:

scope:{
  localClickFunc: "&click",
  myLocalDbClickFunc: "&dblclick"
} ...

 <myButton  ng-click="localClickFunc($event)" ng-doubleckick="myLocalDbClickFunc($event)"/>

there are many other events (mouseover etc)

my localClickFunc are binded in scope directive with controller functions(they could be binded with "=" for my case It doesn't matter).

The problem is that in the usage of this 'myButton' directive not all attributes are necessary .If I use it with all the other events will get registered and fired through angular to a noop function.

I can have as many as 1000 buttons on the screen .What would be the solution to this ?. Are there conditional templates ?

Upvotes: 2

Views: 1582

Answers (2)

Nikos Paraskevopoulos
Nikos Paraskevopoulos

Reputation: 40298

The ? in the scope binding definition makes the attribute optional.

However, function bindings (&) are always optional, as far as Angular is concerned. I.e. Angular will not complain if you do not specify a function in this binding and it will put a function in the scope of the directive anyway. So you cannot write if( scope.localClickFunc == null ) to check for its existence.

I would suggest to use the optional binding =? to specify the callbacks. This way you will be able to check the scope for the existence of the binding and, only if it exists, bind it to the actual DOM event. Example code:

scope:{
    localClickFunc: "=?click",
    localDbClickFunc: "=?dblclick"
},
link: function(scope, element, attrs) {
    ...
    if( scope.localClickFunc != null ) {
        element.on("click", scope.localClickFunc);
    }
    ...
}

Then use the directive as:

<myButton click="localClickFunc($event)"
          dblclick="myLocalDbClickFunc($event)"
/>

You can specify any or all of the attributes and the handlers will be installed accordingly.

Upvotes: 2

bresleveloper
bresleveloper

Reputation: 6070

u can send the attr like say the directive name is mydir then and then in the link and compile functions one of the 3rd parameter is usually names as params and u get there by params.mydir (value will be ovidiu). you can send anything textbased like ';' seperated like "click;dbclick;onmouseout" and break it in the directive with params.mydir.split(';'). from there you can even go to groups of events like "allClicks", u just need in the link some dictionary or switch that will append the right stuff.

Upvotes: 0

Related Questions