简体   繁体   中英

Having more than one controller in a view in AngularJS

I am building an application that contains a left menu bar, and a main content view which has the attribute ng-view . I have configured the router so when the user goes to eg /cars the html that displays all the cars is used together with the CarListController . However, I also would like a controller for the menu-bar (which is the same for all views). Is it right to use the ng-controller attribute on that particular element?

And how about using multiple controllers on the same view (Angular view, the content inside ng-view)? I mean, if you have a created a component such as a contact-form where there are code for events on buttons etc. Instead of duplicating this functionality if you use the contact form inside another view, can you use the ng-controller on that html element containing the contact-form? Is that considered bad usage of it?

  1. Yes you can use multiple controller in one view with ng-controller
  2. It's not a bad practice.
  3. If you think it's a component that you can separate to a directive, it would be better. Since directive is all about a component that can do a specific task and it has it's own controller and scope. And It's easier to test too !

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