We can create multiple controller in Angular JS Application. Almost all project have the requirement to use multiple controller in Angular JS. Each controller have different responsibility and functions depends upon our requirements. Let’s consider following example, which shows that how can we create multiple controller in an Angular JS Application.
Multiple Controller in Angular Js Application
<!DOCTYPE html>
AngularJS Demo
<body>
Today is {{day || "(unknown)"}}
Tomorrow is {{day || "(unknown)"}}
</body>
</html>
We have added a controller called tomorrowCtrl
that works out tomorrow’s name. We have also edited the HTML
markup so that each controller has its own view. You can notice that, how we are able to use the day property in both views without the values interfering with each other. Each controller has its own part of the overall application scope, and the day property of the dayCtrl
controller is isolated from the one defined by the tomorrowCtrl
controller. You would not create two controllers and two views for such a simple application in the real world, but we want to demonstrate the different features of modules, and this is a good foundation for doing so.
Using the Fluent API
The result of the methods defined by the Module
object is the Module
object itself. This is an odd-sounding but
neat trick that allows for a fluent API, where multiple calls to methods are chained together. Let’s consider following sample example, We can rewrite the script element from above example without needing to define the myApp
variable, as shown below.
...
...
We call the angular.module
method and get a Module
object as the result, on which we immediately call the
controller method to set up the dayCtrl
controller. The result from the controller method is the same Module
object that we got when we called the angular.module method, so we can use it again to call the controller method
to set up tomorrowCtrl
.
As this article is also a part of Concepts while working with Angular JS Application . So, you must read other tutorials in order to complete understanding to developing Angular JS Application. Since, we are going to learn several concepts. That's why I have broken this article into several small article. Which allow us to easily understand several Angular JS features and concepts. Following are the list of articles.
Summary: You should read above mentioned articles in order to completely understanding to developing an Angular JS application. This article is a part of Concepts while working with Angular JS Application, which is divided in to pieces of tutorials in order to understand easily. I hope you will like this article and find it useful.