Sabyasachi
Sabyasachi

Reputation: 531

Can two different modules have controllers with the same name in angular js?

I am making my first app in Angular JS.

I have a three Tab Website.

So how should the angular modules be defined? One for each page and one main module which controls all three page?

I wanted to ask if this is possible?

Upvotes: 4

Views: 3662

Answers (3)

requenaxii
requenaxii

Reputation: 131

Yes, you can. But it's good practice isolate logic from HTML document as far as possible.

For example.


App.js

app.controller("PanelController", function() {
 this.tab = [youTabId]; // Set a tab by default on load. 

 this.selectTab = function(setTab) {
  this.tab = setTab;
 };

 this.isSelected = function(checkTab) {
  return this.tab === checkTab;
 };
});

In HTML, on your tab section, add a controller with ng-controller like this ng-controller="PanelController as panel".

For each <li> add an ng-class like this ng-class="{active : panel.isSelected([yourTabId])}".

And for each link <a> an ng-click, ng-click="panel.isSelected([youTabId])".

By this way, on your <div> to show when click on a tab, add an ng-show="panel.isSelected([yourTabId])"


With this, your code is clean and adaptable.

Upvotes: 1

Johannes Reuter
Johannes Reuter

Reputation: 3547

You can create three controllers in three different modules under the same name, but if you import the three modules in your main application, a name collision will happen and only the last controller will be available (Modules and namespace / name collision in AngularJS).

The angular module system makes sense if you want to re-use part of your application in another project or have a real big application with lots of services, filters etc. . Since this is not the case for your small three tabs website, I would suggest to use one module for your app and three different controllers in this module.

angular.module('app', [])
.controller("tab1", function() {
    })
.controller("tab2", function() {
    })
.controller("tab3", function() {
    });

Upvotes: 3

Chanu De Silva
Chanu De Silva

Reputation: 426

If there are three different pages, you have to make three controllers. It's good practice and later you can manage your application properly.

You have to create one module and implement three controllers.

var app = angular.module('myApp', []);

And then you have to create controllers.

app.controller("myCtrl", function($scope) {
   $scope.firstName = "John";
   $scope.lastName = "Doe";
});

This is the best structure. Keep this up :)

Upvotes: 1

Related Questions