Injecting a controller into an AngularJS module within an anonymous function

As a newcomer to the world of javascript and just beginning to work with angular.js, I have a question.

I'm wondering if there is a method for injecting a controller into a module that is declared within an anonymous function.

This is how my code currently appears:

app.js

(function(angular) {
    var app = angular.module('Organizer', ['ngMaterial', 'ngAnimate', 'ngAria']);
})(angular);

siteController.js

(function(angular, app) {
    app.controller('site', function($scope, $mdDialog)
    {
        var alert = $mdDialog.alert({
            title: 'Test',
            content: 'Testing',
            ok: 'Exit'
        });

        $mdDialog.show(alert);
    });
})(angular);

I've attempted to find solutions on whether this is possible, but I am eager to hear explanations from anyone here who may know how to achieve this.

Note: While I have previous experience with angular.js, I wanted to explore a different approach for declaring controllers in order to prevent client modifications.

Answer №1

If you develop a module using Angular, it cannot be obscured in this manner. Users can easily access your app by running angular.module('Organizer') in the console and then executing any desired method.

The issue with your code not functioning as intended is due to the lack of passing the app variable to your unnamed function. To add a controller to the Organizer module, you should follow this pattern:

(function(angular)
{
    angular.
      module('Organizer').
      controller('site', function($scope, $mdDialog)
      {
          ...
      });
})(angular);

Answer №2

There is no necessity to enclose any of this code within self-executing functions in an attempt to prevent variables from polluting the global scope. The sole global object is "angular".

Your app.js file should contain only:

'use strict';
angular.module('Organizer', ['ngMaterial', 'ngAnimate', 'ngAria']);

Your controller file should contain only:

'use strict';
angular.module('Organizer').controller('siteController', function($scope, $mdDialog) {
    var alert = $mdDialog.alert({
        title: 'Test',
        content: 'Testing',
        ok: 'Exit'
    });

    $mdDialog.show(alert);
});

The initial call to module in app.js includes the second parameter that angular utilizes for instantiating your module. Any subsequent calls that do not include the second parameter "retrieve" the module.

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

"Enhance your data visualization with Highcharts Windbarb and effortless AJAX data

Alright. Let's rephrase a question that hasn't been answered yet. I've got a chart below with data loading dynamically via ajax. A simplified version (without ajax) of this graph works well as shown in this jsfiddle. The code below represe ...

The issue arises when the export function is triggered within the getStaticPaths() method, preventing the top-level

For my Next.js SSG (static site generation) app, I decided to optimize the database connection process by exporting a global promise from one file and then utilizing it in another file called controllers.js. This file houses multiple functions that directl ...

Incorporating Progressive Web App Support into a JavaServer Faces Web Application

Exploring the possibility of integrating Progressive Web App support into a JavaServerFaces web application has become a focal point for our team. As our JSF app continues to evolve, we foresee the need to provide offline access to certain parts of the app ...

Implement lazy loading for scripts in Next JS

Currently working on a project with Next JS and focusing on optimizations through Google's Page Speed Insights tool. One major performance issue identified is the presence of 3rd party scripts, specifically the Google Tag script (which includes Google ...

Obtaining the image with PHP

As a newcomer to PHP and Ajax queries, I am trying to utilize the croppie.js plugin to upload a profile image. However, when I upload the image, it is saved as 1580192100.png. The problem arises when attempting to later retrieve the image based on the user ...

Tips for including a JWT token as a query parameter in NEXT js?

const UserJwt = (props) => { const { jwt } = props; const [jwtToken, setJwtToken] = useState(null); useEffect(() => { if (jwt) { setAuthToken(jwt); setJwtToken(jwt); } }, [jwt]); return <MobilePurchaseScreen {...pro ...

React.js issue with onChange event on <input> element freezing

I am experiencing an issue where the input box only allows me to type one letter at a time before getting stuck in its original position. This behavior is confusing to me as the code works fine in another project of mine. const [name, setName] = useStat ...

Is there a way for me to identify the vertical gaps in my code using JavaScript?

Within this specific HTML document, there are multiple div elements that have an absolute positioning applied to them I am looking to develop a JavaScript code that can determine the row of each individual div. I define a row as any space on the vertical ...

In React, facing difficulty in clearing setTimeout timer

After clicking the button, I want my code to execute 3 seconds later. However, I'm having trouble achieving this. It either runs immediately or doesn't stop running. <Button onClick={setTimeout(() => window.location.reload(false), 4000), cl ...

Issue found when utilizing ngRepeat. Checkbox and radio button statuses being incorrectly set

In the controller of my component, I have an array of users that I attempted to display using the ngRepeat directive. However, there are some bugs in the output: Only the second user should have the active property set to true. The second radio button sh ...

Issue with isNan() and typeof in React framework

I'm attempting to create a field in the react-bootstrap component that only accepts numeric input. I know there is a type="number" attribute that can be used, but it's currently set to password to mask the input. Initially, I tried this approach ...

Navigating through Sails.Js: A Guide to Implementing Pagination

Looking to implement paginated tables in your application using sails.js, mongodb, and waterline-ORM? Wondering if there is a recommended method for pagination in sails.js? ...

Material Design Forms in Angular: A Winning Combination

I'm currently working on developing a form using Angular Material. This form allows the user to update their personal information through input fields. I am utilizing "mat-form-field" components for this purpose. However, there are certain fields tha ...

Encountering an Internal Server Error while setting up a Next.js Application

I recently decided to dive into Next.js and followed the tutorial on their official website, but unfortunately, I hit a roadblock. When I run npm run dev, I encounter the following error messages in my console and terminal: Failed to load resource: the ser ...

Learn the process of extracting an array of objects by utilizing an interface

Working with an array of objects containing a large amount of data can be challenging. Here's an example dataset with multiple key-value pairs: [{ "id": 1, "name":"name1", age: 11, "skl": {"name": & ...

Is it possible to customize the selected color of the Chip component?

Is there a way to change the clicked color of a Chip component without modifying the theme.js file? I attempted to override the classes with the desired colors, but it still defaults to primary/secondary colors. This information was found in the source co ...

What is the best method for retrieving key-value pairs from an object based on a specific string filter?

const obj = { "pi_diagram": null, "painting": null, "heat_treatment": null, "welding_procedure": null, "inspection_test": null, "pipecl_hadoop": null, "pipecl": null, "ludo_min_hado ...

What do you prefer: defining properties with the JSON object or with objectName.property in JavaScript

Can you tell me which approach is considered the best practice? Is it better to use the "this" statement in the following way: var obj = { x: 20, y: 10, width: this.x, height: this.y, render: function () { // renders object on canvas ctx.fi ...

Search for elements with a specific substring in their class names using the querySelectorAll() method

I'm working with a custom component in app.js return ( {cards.map((index) => { return <Card key={index} /> ) Within the Card component, I assigned a specific className return ( <ListItem id="root" className="find-card"&g ...

What is the best way to shift a list to the right within my navigation bar using ReactJS and CSS?

I'm looking to align a list to the right in my navbar, as shown in the image below Image Here's my navbar.js code: import React from "react"; import "./Navbar.css"; const Navbar = ({ isScrolling, information }) => { ...