How to use controller with custom directive in AngularJS?

48 Views Asked by At

Let's say I am using a custom directive named my-form-data:

<my-form-data info='infoObj1' template="ssc.html"/>
<my-form-data info='infoObj2' template="college.html"/>

Inside directive definition, I want a different templateUrl based on the template attribute of the directive on the HTML page.

Is there any way to specify the controller class associated with ssc.html and college.html?

1

There are 1 best solutions below

2
On

Use different directives. Its just a couple lines of code and they'll have their own template HTML. They can all share the same controller if desired or have their own. It doesn't make sense to try and use the same directive if you have different views and different controllers.

To answer your question directly, you can specify the controller in your directive HTML using ng-controller.

ssc.html

<div ng-controller='sscCtrl'> 
... 
</div>

college.html

<div ng-controller='collegeCtrl'> 
... 
</div>