简体   繁体   中英

How to use controller with custom directive in AngularJS?

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?

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>

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM