AngularJS: incorporating modules across distinct controllers

Imagine we have two distinct AngularJS controllers housed in separate files that are both referenced in an HTML document. Here's how it looks:

//controller1.js
"use strict";
var someApp = angular.module('MYAPP');
//var someApp = angular.module('MYAPP',['ngCookies']); <-- Does not work

someApp.controller('Controller1', function($scope) {

    $scope.CookieFunction = function(){
        //foo
    };
});   


//controller2.js
"use strict";
var someApp = angular.module('MYAPP',['ngCookies','ui.bootstrap']);

someApp.controller('Controller2', function($scope,$cookies) {

    $scope.SomeOtherfunction = function(){
        //foo
    };
}); 

//HTML file
<script src="controller1.js"></script>
<script src="controller2.js"></script>

Within controller1, there is a need to execute Cookie operations which necessitates the inclusion of ngCookies. However, if this inclusion occurs inside controller1.js, it results in controller2 becoming undefined. The preference lies in adding modules precisely where they are required and not elsewhere. How can this be accomplished without impacting subsequent controllers?

EDIT: Upon moving the inclusion of ngCookies from controller2 to controller1, the following error is encountered (Argument 'controller2' is not a function, got undefined)

Answer №1

If you want to modularize your application, one way to do it is by creating different modules like the example below. This approach is recommended for maintaining a structured and organized application.

 //app.js
"use strict";
var mainApp = angular.module('MYAPP', ['SomeApp', 'OtherApp']);


 //controller1.js
var someApp = angular.module('SomeApp',['ngCookies']);
someApp.controller('Controller1', function($scope,$cookies) {

    $scope.CookieFunction = function(){
        //foo
    };
});   


//controller2.js
"use strict";
var otherApp = angular.module('OtherApp ',[]);

otherApp.controller('Controller2', function($scope) {

    $scope.SomeOtherfunction = function(){
        //foo
    };
}); 

//HTML file
<script src="app.js"></script>
<script src="controller1.js"></script>
<script src="controller2.js"></script>

Answer №2

By providing a second argument to angular.module, like

angular.module('MYAPP',['ngCookies'])
, you are creating a brand new module along with its necessary dependencies. If you omit the second argument (dependencies), then the function functions as a 'getter', returning a reference to the existing module that can be used to register additional controllers/services/etc. Repeating
angular.module('MYAPP', ['ngCookies'])
will overwrite the original 'MYAPP' module, causing Controller1's functionality to appear lost.

Since ngCookies is already included via `angular.module('MYAPP',['ngCookies']) in the same file as Controller2, there is no need to repeat it in the file containing Controller1. You should be able to access $cookies just fine in Controller1 - just remember to inject it properly. For example:

someApp.controller('Controller1', function($scope, $cookies) {

    $scope.CookieFunction = function(){
        //foo
    };
});

Answer №3

Perhaps something along these lines?

//app.js
"use strict";
angular.module('MYAPP', ['myCtrl1', 'myCtrl2']);

//controller1.js
angular.module('myCtrl1', ['ngStorage'])
  .controller('Controller1', function($scope) {

    $scope.StorageFunction = function(){
        //bar
    };
});   

//controller2.js
"use strict";

angular.module('myCtrl2',['ngStorage','ui.router']);
  .controller('Controller2', function($scope,$localStorage) {

    $scope.SomeOtherfunction = function(){
        //bar
    };
});

//HTML file
<script src="app.js"></script>
<script src="controller1.js"></script>
<script src="controller2.js"></script>

Answer №4

The issue within the code snippet is as follows (replace [ngCookies] with ['ngCookies'])

//controller1.js
"use strict";
var myApp = angular.module('YOURAPP',['ngCookies']);

Another method, condensing into 1 app.js file

// app.js
"use strict";
var myApp = angular.module('YOURAPP',['ngCookies']); 

myApp.controller('Controller1', function($scope) {

    $scope.CookieFunction = function(){
        //foo
    };
});   

myApp.controller('Controller2', function($scope,$cookies) {

    $scope.SomeOtherfunction = function(){
        //foo
    };
}); 

//HTML file
<script src="app.js"></script>

Combining into a single main app.js with separate controller files

If you prefer to have controllers in distinct files, then,

app.js

var app = angular.module("testApp",['ngCookies','ui.bootstrap']);

test1.js

app.controller("controller1",function(){
// some code
})

test2.js

app.controller("controller2",function(){
// some code
})

Lastly, include the JS files in the HTML

<script src="app.js"></script>
<script src="controller1.js"></script>
<script src="controller2.js"></script>

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

initialize a while loop in the $scope

Is it possible to create a scope inside a loop similar to JavaScript's var data + [i]? I believe it is, and I want to push some data to the scope in this manner. for (var i = 0; i < $scope.laporanDataKuisioner.contents.length; i++) { ...

Tips for adding JSON values to an object

There is a specific object called SampleObject which has the following structure: { ID: "", Name: "", URL: "", prevName: "", Code: "", } I am looking to insert the values from the JSON object below (values only): var object = { "Sample ...

Utilize the fetch function to showcase information retrieved from a specific endpoint on a webpage using Javascript

Hey there, I have a Node server with an http://localhost:3000/community endpoint. When I make a GET request to this endpoint, it returns information about three different users in the form of JSON objects. [ { "avatar": "http://localhost:3000/avatars ...

Using jQuery in an external JavaScript file may encounter issues

As a newcomer to jQuery, I decided to try writing my jQuery code in an external js file rather than embedding it directly into the head of the HTML file. Unfortunately, this approach did not work as expected. Here is what my index.html looks like: < ...

Implementing react router functionality with Material-UI tabs

Could you please provide some insight on how to integrate my routes with MUI tabs? I'm not very familiar with MUI and could use some guidance on how to get it working. Any suggestions would be appreciated. To simplify the code, I have removed the imp ...

Get the npm distribution package without the need to actually install npm

Is there a way to obtain an npm package without the need for running npm view XXX ... or installing node/npm? Specifically, I am attempting this process on a Linux operating system. ~UPDATE~ I now understand that I should have provided more details about ...

Leverage the Power of Two AngularJS Factories

Can I efficiently use two Factories in AngularJS by calling one from the other? Here's the Scenario: I have a Factory that returns an Array. This Factory is responsible for checking if the data to populate this Array already exists in local SQL Stor ...

Include an HTML attribute within a given string

Using jQuery, I am adding HTML content to a div. The variables rowString and inputString have been defined beforehand: $("#filterContainer").append( rowString + `<label class='filterLabel' for=${filter}>${filter}< ...

What is the best way to create a jumping animation for an object in Cannon.js and Three.js?

During my quest for a solution, I came across a common practice where users used cannonBody.velocity.y = JUMP_VELOCITY to make an object jump. However, in my scenario, this method only worked while the object was already in motion and not when it was stat ...

The Express server is failing to deliver a response to the client when using the fetch method

Currently, I am utilizing express for the server side of my project. To send a post request from the client to the server, I am using fetch. The data that I am sending to the server is being successfully transmitted and displayed. However, I am encounteri ...

What is the best way to place a floating elastic div on top of an elastic background and ensure that the div stays in place?

Looking for some creative input here. Don't have a specific question in mind, but open to ideas. Just to clarify, I want both the floating div and the background to resize as the window size changes, while keeping the div in the same position on top ...

Locate the present position of the slider element

I am currently in the process of creating a website that features pages displayed in a slider format. Each page has its own unique ID, but all share a common class called 'section'. However, I am encountering difficulty in identifying the ID of t ...

Implementing conditional validation in Formik on cancel button click in a React application

When defocusing from the field without entering any data, a validation error occurs. Similarly, if you click on the submit button without giving a value, a validation error is triggered - this behavior is expected. However, how can we prevent the validat ...

Combining two observable entities

Utilizing Angular 4 and rxjs, the objective is to fetch data from two distinct servers in JSON format, merge this data, and exhibit it in a list by associating the list with an observable array. **Word Search Component TypeScript File:** @Component( ...

When conducting unit testing with Express, encountering an error message such as "`call of undefined`" may indicate that

In my current quest to test a node.js application using express, I encountered an issue. After successfully returning a simple 404.html page, I attempted to close the node http server, resulting in an error: Fatal error: Cannot call method 'call&apos ...

The elements within the array have not been defined

Why is the results array showing as undefined? I am having trouble displaying the objects inside the results array. I have attempted to do so with console.log(data.results[0].bodyColor) but encountered an error. When I try accessing (data.results), it ret ...

Can I specify which modal or component will appear when I click on a component?

Working on a small Angular 5 project, I have a simple component that represents a food product shown below: [![enter image description here][1]][1] This component is nested within my main component. When this component is clicked, a quantity component/m ...

Infura makes ten calls to eth_getBlockByNumber for every eth_call request

Currently, I am in the process of creating a straightforward nextjs API route (https://nextjs.org/docs/api-routes/introduction) that is linked to the Ethereum blockchain for executing a view function (which doesn't require any gas) from a smart contra ...

Is there a way to automatically refresh a webpage whenever there are changes

Currently, I have a webpage that operates like a reverse auction, complete with a javascript countdown timer that tracks the time remaining in the auction. Once the timer reaches zero, the auction ends and the page automatically refreshes. While everythin ...

Transfer external variables into the image's onload function

I am trying to retrieve image dimensions and then execute additional actions. Since the image onload function is asynchronous, I have decided to handle everything within the onload call. This is my current approach: function getMeta(url, callback) { v ...