Splitting AngularJS Controllers Into Individual Files

I'm currently utilizing Ui-Router in my AngularJS project and I'm seeking a way to organize my angular controllers into separate files for better organization.

For instance:

var app = angular.module('myApp', ["xeditable", 'ngRoute','ngSanitize',
 'ngAnimate', 'ngAria', 'ngMaterial','ngFileUpload','ui.router']);

app.config(function($stateProvider, $urlRouterProvider){

// For any unmatched url, redirect to /route1
$urlRouterProvider.otherwise("/my_requisitions/list");

$stateProvider
    .state('my_requisitions', {
        url: "/my_requisitions",
        templateUrl: "../../../partials/requisitions/my_requisitions.ctp",
        //controller: 'my_controller'
    })
    .state('my_requisitions.list', {
        url: "/list",
        templateUrl: "../../../partials/requisitions/my_requisitions.list.ctp",
        //controller: 'my_controller'

    })
    .state('my_requisitions.add', {
        url: "/add/:type",
        templateUrl: "../../../partials/requisitions/my_requisitions.add.ctp",
        controller: 'my_controller'

    })
    .state('manage_requisitions', {
        url: "/manage_requisitions",
        templateUrl: "../../../partials/requisitions/manage_requisitions.ctp"
    })
    .state('manage_requisitions.list', {
        url: "/list",
        templateUrl: "../../../partials/requisitions/manage_requisitions.list.ctp",
        controller: 'manage_controller'
    })
})

Given this code snippet, how can I move the declaration of 'my_controller' to an external file instead of defining it at the end as seen here:

app.controller('my_controller', function($scope, $filter, $http, $timeout,$mdDialog, $stateParams) {
etc....

Simply referencing the JavaScript file in the main HTML file and then using app.controller() does not seem to be effective. Any suggestions are appreciated!

Thank you!

Answer №1

To ensure proper loading sequence, make sure to include your controller files in the HTML document before declaring your application file.

<script src="/path/to/angular.js"></script>
<script src="/path/to/controller1.js"></script>
<script src="/path/to/controller2.js"></script>
<script src="/path/to/yourapp.js"></script>

Within each controller file, define a controller as follows:

var Controller = function ($scope) {

}

Controller.$inject = ['$scope'];

Once you have declared the app variable in your main file:

app.controller('Controller', Controller);

Answer №2

Consider organizing your controller in a separate file and then including it in your HTML file after you have included your app file

<!DOCTYPE html>

<html>
<head>
<meta name="viewport" content="width=device-width" />
<script src="~/Scripts/angular.js"></script>
<script src="~/Scripts/Demo.js"></script>
<script src="~/Scripts/DemoController.js"></script>
<title>Demo</title>
</head>
<body>
<div ng-app="demoApp">
    <div ng-controller="demoController">
        <span>{{dummyData}}</span>
    </div> 
</div>
</body>
</html>

Code snippet from Demo.js

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

Code snippet from DemoController.js

demoApp.controller('demoController', function($scope) {
     $scope.dummyData = "hello from demo app";
});

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

Eliminating unnecessary whitespace between the bottom of the document and an element

I have a HTML page that when scrolled should limit scroll to the document height. It must not exceed the bottom of an element. Here is a screenshot for better understanding: https://i.stack.imgur.com/RaVg8.jpg The scrolling should be limited after the En ...

Having difficulty accessing the API response accurately

The response from my API is as follows: {"__v":0,"short":"8xdn4a5k","_id":"5404db5ac27408f20440babd","branches":[{"version":1,"code":""}],"ext":"js","language":"javascript"} When I use this code, it works perfectly: console.log(response.short); However ...

javascript pull data from an array

As a novice in HTML and JavaScript, I have a brief code snippet that embeds multiple audio files. I am utilizing a loop and would like to utilize strings from an ARRAY as the sources for the WAV files (rather than just "file1.wav"). Thank you. <!DOCT ...

Change the spread operator in JavaScript to TypeScript functions

I'm struggling to convert a piece of code from Javascript to Typescript. The main issue lies in converting the spread operator. function calculateCombinations(first, next, ...rest) { if (rest.length) { next = calculateCombinations(next, ...res ...

Creating dynamic height based on width using JavaScript

I'm trying to make a rectangle responsive based on the width of the window. This is my current logic: aspectRatio = 16 / 9 win = { width: window.innerWidth, height: window.innerHeight, } get browser() { const width = this.win.width - 250 ...

How can I confine a non-UMD module that has been imported in Webpack and Typescript to just one file?

When working on a project that involves Typescript and Webpack, I want to make sure that global libraries, such as jQuery, are treated as UMD globals. Currently, if I do not include import * as $ from 'jQuery' in a file where I am using $, webpa ...

What is the proper way to integrate three.js (a third-party library) into the view controller of an SAPUI5 application

Seeking a Solution Is there a way to integrate the three.js library into SAPUI5 in order to access it using THREE as the root variable in my main view controller? I attempted to create a directory named libs within my project folder and include it in the ...

Material UI DateTimePicker Displaying Incorrectly

I am implementing a new Material UI date time picker on page load by setting the open prop. <Grid item xs={6} className={styles.CampaignDates_calendar_right}> <MuiPickersUtilsProvider utils={DateFnsUtils} className={styles.CampaignDates_calendar ...

Tips on displaying tooltips on multiple graphs in Highcharts using Vue 3

I am currently utilizing vue3-highcharts in conjunction with Highcharts. My goal is to replicate a similar functionality as shown in this example: https://codepen.io/lzl124631x/pen/KLEdby?editors=1010. However, I am unsure about the correct syntax for impl ...

Change the timestamp 2017-09-12 00:00:00 to just 2017-09-12 with the help of Angularjs

When pulling data from the database, the date is showing up as 2017-09-12 00:00:00. How can I format it to only display as 2017-09-12? ...

Passing the results of sequelize through express after the completion of a forEach iteration

In an express route, I am running a somewhat complex sequelize query that requires me to run a second query afterward to append necessary data to the result: //Get inboxes based on passed params router.get('/:data', function(req, res, next) { ...

How can I navigate through a webpage using Selenium WebDriver and JavaScript?

Currently, I am utilizing the JavaScript API for selenium-webdriver and my goal is to scroll/move down a page in a gradual manner to facilitate visual inspection. Although I am aware that the code below will direct me immediately to a link at the end of t ...

When a user inputs in the field, it automatically loses focus

An error is encountered in two scenarios: When the input includes an onChange event handler When the input is located within a component that is called on another page For instance: In Page1.js, we have: return <div> <Page2 /> </div ...

Exploring the execution of asynchronous scripts in Selenium

Having relied on selenium (using python bindings and occasionally protractor) for quite some time now, every instance I required to run a javascript code, I turned to the trusty execute_script() method. For instance, when it came to scrolling down a page ( ...

The absence of multiple lines on the x-axis in the linear chart was noticeable

Currently, I am facing an issue with loading a single axis line chart on my Dashboard.vue. The functionality involves users selecting a 'year' and a 'loan_type' from dropdown menus, after which the chart should display a 12-month record ...

incorporating a dynamic parameter into the payload of an AJAX post request

I'm currently working on a function call where I want to extract the value of the variable data and place it in the data section of the function. However, despite my efforts, I haven't been successful so far. In PHP, I am attempting to retrieve t ...

Access your Facebook account securely with Single Sign-On integration in Angular

how to resolve this issue The Application configuration forbids the specified URL: The provided URLs do not conform with the App's settings. They should either match the Website URL or Canvas URL, or the domain must be a subdomain of one of the App&a ...

Can anyone provide guidance on uploading data to a mongodb database? I've attempted a few methods but keep encountering errors

const info = { name, price, quantity, image, desc, sup_name, email } fetch('https://gentle-plateau-90897.herokuapp.com/fruits', { method: 'POST', headers: { 'content-type': 'application/jso ...

What is the process for saving information to a database with JavaScript?

I am currently utilizing the Google Maps API for address translation, primarily through the use of a geocoder. I am interested in saving these results to a local database for future reference, as there are limitations on the total number and frequency of ...

What is the ideal destination for my Ajax request to be sent?

When utilizing jQuery, in the event of sending an Ajax request you must provide the URL to direct towards. For instance: $.get("someurl", function(data) { console.log(data); }); The query at hand is: should the URL indicate a page on the server, trea ...