AngularJS Issue [$injector:modulerr]

My AngularJS module, developed following these tutorials, is not working properly in conjunction with ASP.NET MVC. I have encountered an error [$injector:modulerr] and I am unsure of how to resolve it.

(function () {
    var AAngScript = angular.module('AAngScript', ['ngRoute']);
    AAngScript.controller('LoginController', ['$scope', '$routeParams', '$location', 'LoginFactory', function ($scope,
        $routeParams, $location, LoginFactory) {
        // Controller code goes here
    }]);
    // Other controller and factory declarations follow...
}());

I have included the Angular module in a partial view _Layout using the following code:

<html ng-app="AAngScript">
<head></head>
<body>
    // Scripts and styles included here
    <script src="~/Scripts/angular.min.js"></script>
    <script src="~/Scripts/angular-route.min.js"></script>
    <script src="~/Scripts/AAngScript.js"></script>
    // Other script includes
</body>
</html>

Any help would be greatly appreciated. Thank you!

Answer №1

The closing of the Immediately Invoked Function Expression (IIFE) in your code snippet is not correct. It should be:

})();

This is the correct format:

(function ( /* IIFE enclosed code within this function*/) {

    ...
    ...  

})();

Additionally, you are injecting services into your configuration that should not be injected. You can use services within configuration functions without explicit injection, similar to function parameters.

Here is your code snippet following a coding standard closer to John Papa's Angular Style Guide:

(function () {

    // module definition
    var AAngScript = angular.module('AAngScript', ['ngRoute']);

    // Add controller to angular app
    angular.module('AAngScript').controller('LoginController', LoginController);

    // Inject dependencies into controller
    LoginController.$inject = ['$routeParams', '$location', 'LoginFactory'];

    // Define login controller
    function LoginController($routeParams, $location, LoginFactory){

        // vm as in view-model
        var vm = this;

        vm.loginForm = {
            emailAdress: '',
            password: '',
            rememberMe: false,
            returnUrl: $routeParams.returnUrl,
            loginFailure: false
        };

        vm.login = function () {
            var result = LoginFactory($scope.loginForm.emailAdress, $scope.loginForm.password, $scope.loginForm.rememberMe);
            result.then(function (result) {
                if (result.success) {
                    if ($scope.loginForm.returnUrl !== undefined) {
                        $location.path('/productcategory');
                    } else {
                        $location.path($scope.loginForm.returnUrl);
                    }
                } else {
                    $scope.loginForm.loginFailure = true;
                }
            });
        }
    }


    // Add controller to angular app
    angular.module('AAngScript').controller('RegisterController', RegisterController);

    // Inject dependencies into controller
    RegisterController.$inject = ['$location', 'RegistrationFactory'];

    // Define register controller
    function RegisterController ($location, RegistrationFactory) {

        // vm as in view-model
        var vm = this;

        vm.registerForm = {
            emailAdress: '',
            password: '',
            confirmPassword: '',
            registrationFailure: false
        };

        vm.register = function () {
            var result = RegistrationFactory($scope.registerForm.emailAdress, $scope.registerForm.password, $scope.registerForm.confirmPassword);
            result.then(function (result) {
                if (result.success) {
                    $location.path('/routeOne');
                } else {
                    $scope.registerForm.registrationFailure = true;
                }
            });
        }
    }


    // Add factory to angular app
    angular.module('AAngScript').factory('AuthHttpResponseInterceptor', AuthHttpResponseInterceptor);

    // Inject dependencies into factory
    AuthHttpResponseInterceptor.$inject = ['$q', '$location'];

    // Define AuthHttpResponseInterceptor factory
    function AuthHttpResponseInterceptor($q, $location) {

        var factory = this;

        factory.response =  function (response) {
            if (response.status === 401) {
                console.log("Response 401");
            }
            return response || $q.when(response);
        }

        factory.responseError = function (rejection) {
            if (rejection.status === 401) {
                console.log("Response Error 401", rejection);
                $location.path('/login').search('retutnUrl', $location.path());
            }
            return $q.reject(rejection);
        }

        // The factory object must be returned. Failure to do so results in an injection error
        // from an undefined factory.
        return factory;
    };


    // Add factory to angular app
    angular.module('AAngScript').factory('LoginFactory', LoginFactory);

    // Inject dependencies into factory
    LoginFactory.$inject = ['$http', '$q'];

    // Define LoginFactory
    function LoginFactory($http, $q) {

        var factory = this;

        factory.login = function(emailAdress, password, rememberMe){

            var deferredObject = $q.defer();

            $http.post(
                    '/Account/Login', {
                    Email: emailAdress,
                    Password: password,
                    RememberMe: rememberMe
                }
            ).
            success(function (data) {
                if (data == "True") {
                    deferredObject.resolve({ success: true })
                } else {
                    deferredObject.resolve({ success: false })
                }
            }).
            error(function () {
                deferredObject.resolve({ success: false })
            });

            return deferredObject.promise;
        }

        // The factory object must be returned. Failure to do so results in an injection error
        // from an undefined factory.
        return factory;
    };


    // Add factory to angular app
    angular.module('AAngScript').factory('RegistrationFactory', RegistrationFactory);

    // Inject dependencies into factory
    RegistrationFactory.$inject = ['$http', '$q'];

    // Define RegistrationFactory
    function RegistrationFactory($http, $q) {

        var factory = this;

        factory.register = function(emailAdress, password, rememberMe){

            var deferredObject = $q.defer();

            $http.post(
                '/Account/Register', {
                    Email: emailAdress,
                    Password: password,
                    ConfirmPassword: confirmPassword
                }
                ).
            success(function (data) {
                if (data == "True") {
                    deferredObject.resolve({ success: true });
                } else {
                    deferredObject.resolve({ success: false });
                }
            }).
            error(function () {
                deferredObject.resolve({ success: false });
            });

            return deferredObject.promise;
        }

        // The factory object must be returned. Failure to do so results in an injection error
        // from an undefined factory.
        return factory;
    };


    // Add configuration to angular app
    angular.module('AAngScript').config(Routing);

    // define configuration
    function Routing($routeProvider, $httpProvider){

        $routeProvider.
        when('/register', {
            templateUrl: 'Account/Register',
            controller: 'RegisterController'
        })
        .when('/login', {
            templateUrl: '/Account/Login.html',
            controller: 'LoginController'
        });

        $httpProvider.interceptors.push('AuthHttpResponseInterceptor');
    }

})();

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

The side menu in Bootstrap dropdown experiences a one-time functionality

When navigating through a responsive top menu with Bootstrap, everything works seamlessly - from toggling the menu to dropdown functionality. However, I encountered an issue with the side menu as nav-pills used to select tab-panes. <div class="containe ...

The proxy encountered a TypeError when the trap for the property 'set' returned a falsish value

After migrating my code from using es5 class prototype representation to es6 class representation, I encountered an error. This is the comparison of the code before and after migration: ES5 syntax function RoutingScreen (context) { Object.assign(this, ...

Identifying modifications to the content of a text area

Is there a way to determine if the value in my textareaId has changed due to JavaScript? For example: $("#buttonID").on("click, function(){ $("#textareaID").val("lorem ipsum"); }); $("#textareaID").change(function(){ //not working }); $ ...

Exploring the benefits of utilizing useState and localStorage in Next.js with server-side

Encountering an error consistently in the code snippet below: "localstorage is not defined" It seems like this issue arises because next.js attempts to render the page on the server. I made an attempt to place the const [advancedMode, setAdvanced ...

Testing for connected components with a specific property (React/Redux)

Having a React component with Redux @connect decorator, a situation arises like this: import React, { Component } from 'react' import { connect } from 'react-redux' @connect(mapStateToProps, { onPress: () => {...code}) // The ...

The setInterval function with a time interval set to 1ms does not appear to function exactly as a 1ms delay

I'm attempting to measure the duration of a file download using an HTTPRequest as seen below: function getFile() { 'use strict'; var url = "data.bin"; var rawFile = new XMLHttpRequest(); var timer_var = setInterval( theTimer ...

Is it achievable to craft a Twitter Bootstrap 'nav-tabs' menu without altering the URL?

I am looking for a way to implement nav-tab functionality without the URL changing, while still being able to display different tabs with relevant information. My website is built using angularjs, and whenever the page refreshes, it redirects the user bac ...

Set a background image URL for a specific division inside a template

I have a drawPlaceDetails function that populates an HTML template with values. The getPhotoURL() function retrieves a URL link to an image, which I am trying to assign to the background-image property. However, the div remains empty without displaying the ...

How come I am unable to terminate this Angular HTTP request?

I've been trying to implement a solution for canceling HTTP requests in AngularJS by referring to this Stack Overflow post. Here's the code snippet I'm using: var canceller = $q.defer(); $timeout(function() { canceller.resolve(); alert ...

Guide to saving an http response as a file and automatically retrying on a 503 error

When it comes to piping the response of an http request to a file, the process is pretty straightforward: http.get(url, function (res) { var file = fs.createWriteStream(filename) res.pipe(file) file.on('finish', function () { file.clos ...

How can you create a basic slideshow without relying on jQuery to cycle through images?

Imagine you have a div containing 3 images. Is there a way to build a basic slideshow that smoothly transitions between the images, showing each one for 5 seconds before moving on to the next one and eventually looping back to the first image without rely ...

How come the hook keeps triggering endlessly in a loop when I try to pass the updated props?

I've encountered an issue with a custom hook I created for making HTTP requests. The problem is that the request seems to be firing in an endless loop, and I'm unsure of what's causing this behavior. My intention is for the request to only t ...

What is the best way to refresh a page during an ajax call while also resetting all form fields?

Each time an ajax request is made, the page should refresh without clearing all form fields upon loading Custom Form <form method='post'> <input type='text' placeholder='product'/> <input type='number&a ...

Designing an interactive HTML table that adapts to various screen

Currently utilizing Bootstrap to create a responsive HTML table on smaller devices like the iPad, but seeking a more polished and professional alternative. Searching for a JQuery/JavaScript or CSS solution without relying on plugins. Would appreciate any ...

The output does not show the response from the method in React Native

I am facing an issue with a method in my code (React Native). I have an array of IDs and I need to send a 'GET' request for each ID to display a preview card for each. To achieve this, I have used the 'map' method on my array. The req ...

What is the best way to cycle through a series of lists and retrieve the URL when a specific string is found within a class of the list

I'm new to JQuery and currently experimenting on JSFiddle to improve my skills for developing a web app I have in mind. One of the requirements I need to meet is iterating through lists on the page. If a specific class contains a certain string, I sh ...

Error encountered: The initMap function from the React Google Maps API is not recognized. No relevant

Encountering an issue where initMap is not recognized as a function. I attempted to avoid utilizing any additional packages for asynchronously loading the script or Google Maps API. My initial approach was to simply console log initMap to track when the sc ...

Application Path-related Relative Path Problem in MVC Deployment

During the deployment of my MVC Project, I encountered a relative path issue in terms of the server. The project is being hosted as an application in IIS. Once deployed, the URL to access the application will resemble http://localhost/portal/Account/Login. ...

Inventive website concept (far from ordinary, and not a plea for coding assistance)

Once again, I want to clarify that I am not asking for someone to code this idea for me. I am seeking advice from experienced web developers on whether or not my concept is achievable, as it involves some complex issues (at least in my opinion). If this po ...

Highcharts JavaScript - Sankey Graph Axis Orientation

As I work on developing a Sankey Diagram using the Highcharts JS library, I have encountered an issue with setting the axis. Can anyone advise whether it is feasible to utilize xAxis and yAxis in a Sankey diagram? I attempted to define the axis as shown b ...