Organizing controllers in separate files within AngularJS

I've been working on modularizing an AngularJS project by implementing different controllers in their own JS files. However, I'm facing issues with getting them to work properly.

Below is my config.js file where the primary module is defined:

(function() {
var app= angular.module("spa", [

    //oob angular modules


    //3rd party modules
    'ui.router',
    'ui.bootstrap'
]);

app.config(['$stateProvider', '$urlRouterProvider', configRoutes]);

//function to config the routes

function configRoutes($stateProvider, $urlRouterProvider) {

    $stateProvider
    .state('dashboard', {
        url: '/',
        templateUrl: '../App/Views/dashboard.html',
        controller: 'dashboardController',
        controllerAs: 'vm'
    })

    .state('supplier', {
        url: '/suppliers',
        templateUrl: '../App/Views/supplier.html',
        controller: 'supplierController',
        controllerAs: 'vm'
    })

    .state('event', {
        url: '/events',
        templateUrl: '../App/Views/event.html',
        controller: 'eventController',
        controllerAs: 'vm'
    })

    .state('partner', {
        url: '/partners',
        templateUrl: '../App/Views/partner.html',
        controller: 'partnerController',
        controllerAs: 'vm'
    })





    $urlRouterProvider.otherwise('/');

}

app.controller('dashboardController', dashboardController)

function dashboardController() {
    alert('dashboard-same function');
}
}());`

The dashboardController works fine, but other controllers in separate files do not trigger.

(function () {

'use strict';

var app = angular.module('spa');
app.controller('eventController', eventController);

function eventController() {
    alert('event');
}
});

This is the order of my script references:

<!--External Libs-->
<script src="../Scripts/jquery-1.9.1.js"></script>
<script src="../Scripts/angular.js"></script>
<script src="../Scripts/angular-animate.js"></script>
<script src="../Scripts/angular-sanitize.js"></script>
<script src="../Scripts/angular-cookies.js"></script>
<script src="../Scripts/angular-ui-router.js"></script>
<script src="../Scripts/angular-ui/ui-bootstrap-tpls.min.js"></script>   

<!--Jquery Plugins-->

<!--Custom Libs-->
<script src="../App/Common/config.js"></script> 

<!--Controllers-->
<script src="../App/Controllers/event.js"></script>
<script src="../App/Controllers/partner.js"></script>
<script src="../App/Controllers/dashboard.js"></script>
<script src="../App/Controllers/supplier.js"></script>

Thank you for your help.

Answer №1

Regarding my previous comment, it seems like you may have overlooked executing the wrapping function in eventController.js. The correct code should look like this:

(function () {
  'use strict';

  var app = angular.module('spa');
  app.controller('eventController', eventController);

  function eventController() {
      alert('event');
  }
})();
//Don't forget these lines

If this adjustment doesn't solve the issue, I recommend creating a fiddle from your actual local code instead of the fiddle code to avoid any potential typos, and I can assist further.

Additionally, I noticed that there is no reference to routes.js in your HTML file. Did you mean config.html instead?

Answer №2

It seems like there might be some confusion on your end, but I can provide you with an example of how I approach it:

To illustrate, here is my approach to modularizing my AngularJS app (v1.3.6):

index.html:

<html>
<head>
    <title>Modularize</title>

    <!-- load module -->
    <script src="app/app.js"></script>
    <script src="app/app.constant.js"></script>
    <script src="app/app.config.js"></script>
    <script src="app/app.run.js"></script>

    <!-- load controllers/services/directives/factories -->
    <script src="app/controllers/MyController.js"></script>
</head>
<body>
    <!-- REST OF THE APP -->
</body>
</html>

app.js

var myapp = angular.module('spa', ['ui.router']);

app.constant.js

myapp.constant(function () {

});

app.config.js

myapp.config(function ($stateProvider) {
    $stateProvider
        .state('home', {
            url: '/home',
            templateUrl: 'app/views/home.html',
            controller: 'MyController',
        });
});

app.run.js

myApp.run(function () {

});

MyController.js

myapp.controller('MyController', function ($scope) {

});

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Guide to accessing a nested and potentially optional object property with a default value and specifying its data type

Just a simple query here... my goal is to extract data.user.roles, but there's a possibility that data may be empty. In such cases, I want an empty array as the output. Additionally, I need to specify the type of user - which in this instance is any. ...

Having trouble sending an array's JSON data to a web service using Angular

I am working with a table where each cell in the rows contains form fields. The table also has two buttons: one button adds a new row to the table, and the other sends all the rows. Below is the code snippet for adding new blank rows: $scope.attributes = ...

Running HTML code within a DIV using JavaScript

Although I've come across questions like this before, mine has a unique twist. I crafted an HTML code that is capable of running another HTML code within a <div>. The resulting page appears as follows: https://i.sstatic.net/zXgG7.png The HTML ...

The Event of XMLHttpRequest State Transition Error

Can anyone provide assistance in troubleshooting why the code below is not functioning as expected, displaying "something negative happened" instead of the desired PHP echo alert? The JavaScript code I am using is: window.onload = function(){ var re ...

Troubleshooting Problems with Angular Directive Parameters

I'm currently working on a directive that will receive arguments from the HTML and use them to fill in the template fields. Here's the code for the directive: (function(){ angular.module("MyApp",{}) .directive("myDirective",function(){ ...

Exploring additional parameters within express.js

I'm currently working on creating an email sender that includes all necessary components such as 'from', 'to', 'subject', 'textBody', etc. However, I am facing a challenge in setting optional parameters in expre ...

The Django POST request is rejecting due to a missing or incorrect CSRF token, despite having included the token in the form

I'm encountering a 403 response when making a POST request despite including csrf_token in the data for an AJAX request. I made sure that csrf_token is not empty before sending the request, so everything seems correct. What could be causing this error ...

Breaking down a multidimensional array into individual arrays using Javascript

Having a serious problem here, I have an array structured like this: [[0,50],[0,68],[1,26],[2,9],[2,32]] I am looking to split this array into two separate arrays like so: array1 = [[0,50][1,0][2,9]] array2 = [[0,68][1,26][2,32]] Yes, you are correct g ...

Combining Context and MUI's theme provider for effective nesting: A step-by-step guide

Currently, I have a state set up to toggle between dark and light mode on a website that contains numerous nested components. The root App.js file looks like this: function App() { return ( <DarkModeProvider> ...

Step-by-step guide on utilizing the vendor.ts file available at https://angular.io/docs/ts/latest/guide/webpack.html

As per the guidelines provided at https://angular.io/docs/ts/latest/guide/webpack.html, it is recommended to include vendors like jQuery in the vendor.ts file. // Other vendors for instance jQuery, Lodash or Bootstrap // You can import js, ts, css, sass, ...

Change Observable<String[]> into Observable<DataType[]>

I'm currently working with an API that provides me with an Array<string> of IDs when given an original ID (one to many relationship). My goal is to make individual HTTP requests for each of these IDs in order to retrieve the associated data from ...

What is the reason that this jQuery code is exclusive to Firefox?

I am currently working on a code snippet that enables users to navigate back and forth between images by displaying them in a lightbox at full size. The code functions flawlessly in Firefox, however, it does not seem to have any effect on IE, Chrome, and S ...

Utilizing Ternary Operators with User Input

In my latest project, I am developing a cutting-edge app that converts text to sound, utilizing input text from react-native-elements along with ternary operators. My main challenge now is figuring out how to validate whether the text input box is empty ...

Can someone help me understand how to change the structure in order to identify which class has a body?

I have a small example to share with you: link HTML CODE: <div class="body"> <div class="test">TEST</div> </div> JS CODE: switch (className) { //instead of n, I need to write className case body: alert("my cla ...

Hiding the y-axis on a msstackedcolumn2dlinedy Fusion Chart: A step-by-step guide

Currently, I am utilizing the msstackedcolumn2dlinedy fusion charts. To see an example of this in action, please take a look at this fiddle: Fiddle The objective I have is to hide the y-axis value on the right side of this chart. Can anyone provide guida ...

New and improved method for showcasing the switching of two PHP variables using jQuery Ajax

Obtaining two random values from a table in the same row can be achieved using PHP and MySQL. For example: <?php $result = mysql_query("SELECT * FROM people ORDER BY RAND() LIMIT 1", $connection); $row = mysql_fetch_array($result); echo $ro ...

Load an XML file from the local server asynchronously on the Chrome web browser

Attempting to load a local XML/XSL file into a variable for editing seems to be causing an issue. The code provided functions properly in IE and Chrome, however, Chrome displays a warning due to the synchronous nature of the call. function loadXMLDoc(fileN ...

Real-time updating fails to trigger the ng-change event in the text field

I am encountering an issue with a textbox in angularjs. Whenever I update the data in the text field using some method (such as clicking a button), the ng-change event is not triggered. Please take a look at this Plnkr example: [https://plnkr.co/edit/32eE ...

Which is the better option: utilizing the submit event of the form, or incorporating ajax functionality?

Forms are an essential part of my website design, and I often find myself contemplating whether it's better to submit a form using a standard submit button or utilizing Ajax. Typically, I opt for Ajax to prevent the dreaded issue of form re-submission ...

The CSS3 slideshow is displaying distorted and unfocused images

I have a CSS code that controls the timing of my slideshow with 3 images: .slideshow li:child(1) span { background-image: url(../../pic/bg1.jpg); } .slideshow li:child(2) span { background-image: url(../../pic/bg2.jpg); -webkit-animation-de ...