AngularJS presents an error: [ng:areq] The argument 'myAppCtrl' is not recognized as a function, as it returns undefined while implementing routes with ngRoute and $routeProvider

Can anyone assist me with an error I'm encountering while setting routes on two buttons? Despite having everything properly defined, the table is not displaying any data. Your insights would be greatly appreciated.

Thank you for your help.

Snippet from the main HTML file:

//main controller mainCtrl.js:

angular.module("myApp", [])
.controller('myAppCtrl',['getStockData','corsService','$scope', function(getStockData ,corsService, $scope) {

        corsService.enableCors();
       getStockData.getData().then(function(data){

            $scope.products = data;
            console.log("hello from ctrl",data);
           });
    }])
    .controller('salesCtrl', function(getSalesData, $scope){
    getSalesData.getData().then(function(data){
        $scope.salesData = data;
        console.log(data);
    })
})
var app = angular.module("myApp");

//------------------------------------------------------------------------------
//route provider: routeProvider.js:

angular.module("myApp", ["ngRoute"])
    .config(function ($routeProvider) {
        $routeProvider.when("/products", {
            templateUrl: "views/productsView.html",
            // controller:"myAppCtrl"
        })
            .when("/sales", {
                templateUrl: "views/salesView.html",
            })
            .otherwise({
                templateUrl: "views/productsView.html",
                // controller: "myAppCtrl"
            });
    })

.controller("routeCtrl" ,function ($scope, $location){
    $scope.setRoute=function(route){
        $location.path(route);
    }
});

//---------------------------------------------------------------------------------
//getting the data getStockData.js:

app.service('getStockData', function($http){
    var dataUrl = "https://someAPI";
        return {
            getData: function() {
                var successCallback = function (response){
                    //the response object
                    console.log("the response object:", response);
                    return response.data;
                }
                var errorCallback =function (reason){
                    //the reason of error message
                    console.log("error", reason.data);
                    return reason.data;
                }
                //Returns a Promise that will be resolved
                // to a response object when the request succeeds or fails.
                return  $http.get(dataUrl)
                    .then(successCallback, errorCallback);
            }
        }
});
<body>

<div class="navbar navbar-inverse">
    <a class="navbar-brand" href="#">Beerbay</a>
</div>
<div ng-controller="routeCtrl" class="col-sm-1">
    <a ng-click="setRoute('products')"
       class="btn btn-block btn-primary btn-lg">Products</a>
    <a ng-click="setRoute('sales')"
       class="btn btn-block btn-primary btn-lg">Sales</a>
</div>

<ng-view />


</body>

<!--the partial view: productsView.html----------------------------------------->

<div class ="col-sm-11" ng-controller="myAppCtrl">
    <!--displaying the data-->
    <h4>Products</h4>
    <table id="product_table" class="table">
        <thead>
        <tr>
            <!-- table headers removed for brevity-->
        </tr>
        </thead>
        <tbody>
        <tr ng-repeat = "item in products|orderBy: 'name'">

            <!-- table body removed for brevity-->
          <!-- here I am displaying the products from the $scope-->
        </tr>
        </tbody>
    </table>
    </div>

<!--the other partial view: salesView--------------------------------------------->

<body>
<p>This is the sales view</p>
</body>

Answer №1

It seems like you are redundantly declaring the myApp modules twice.

1 ) angular.module("myApp", [])
2 ) angular.module("myApp", ["ngRoute"])

You have defined the myApp controller in the first module, and then proceeded to declare the same module again.

To streamline your code, define the module only once and access it like this:

 var module = angular.module("myApp");

Please make these necessary changes for better optimization.

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

Creating a dynamic display of flash files on a webpage through a unique combination of PHP, AJAX, and

Despite my lack of experience with Ajax and minimal java knowledge, I have a strong background in SQL and PHP. Even though I anticipate criticism for this question, I am determined to seek help. My primary objective is to rotate 4 flash SWF files randomly ...

Create a request for an update by utilizing Axios within a React and Material UI environment

I am completely new to React, and my experience with CRUD functionality is limited to ASP.NET MVC. I'm feeling a bit lost as none of the tutorials I've come across seem to cater to my specific situation. The tips I received previously were helpfu ...

Create a jQuery script that generates clickable links when a user is mentioned in the

Hey there, I've been incorporating this fantastic plugin created by Hawkee into my project. It functions similarly to Twitter, allowing users to @mention others. However, I'm encountering issues with the output when using the following method: u ...

Can Sync blocking IO be implemented solely in JavaScript (Node.js) without the use of C code?

Is JavaScript intentionally designed to discourage or disallow synchronous blocking I/O? What is the reason for the absence of a sleep API in JavaScript? Does it relate to the previous point? Can browsers support more than one thread executing JavaScript? ...

The text color remains the same even after the method has returned a value

I have a vuex query that returns a list of books. I want to display each book with a specific color based on its status. I tried using a method to determine the color name for each book and bind it to the v-icon, but it's not working as expected - no ...

Leverage the power of mathematical functions within Angular to convert numbers into integers

In my Angular 7 Typescript class, I have the following setup: export class Paging { itemCount: number; pageCount: number; pageNumber: number; pageSize: number; constructor(pageNumber: number, pageSize: number, itemCount: number) { thi ...

Sequencing the loading of resources in AngularJS one after the other by utilizing promises

While working in a service, my goal is to load a resource using $http, store it in a variable, load a child resource and store that as well. I understand the concept of promises for this task, but I am struggling with how to properly implement it in my cod ...

Please provide both an image and text in addition to a progress bar by using the form to

I am working on a form that needs to store both images and text data in a database. <form action="processupload.php" method="post" enctype="multipart/form-data" id="UploadForm"> <input name="name" type="text" /> <input name="age" ty ...

Ways to generate an Angular 7 component

Seeking guidance on creating an angular 7 component. I have forked a jsFiddle at this link: https://jsfiddle.net/gauravshrestha/fdxsywLv/. The chart in the fiddle allows data points to be dragged up and down. My goal is to convert this into a component whe ...

Changing the bootstrap popover location

I'm looking to customize the position of a Bootstrap popover that appears outside of a panel. Here's my setup: HTML: <div class="panel"> <div class="panel-body"> <input type="text" id="text_input" data-toggle="popover ...

Trigger a callback in ASP.NET's CallbackPanel using JavaScript every 10 seconds

I am attempting to automatically trigger the callback of a CallbackPanel using JavaScript in my WebFormUserControl every 10 seconds. While I can trigger it with an ASPxButton and ClientSideEvents, my ultimate aim is to have it start automatically every 10 ...

Tips for implementing Peer.js in Next.js using TypeScript?

Next.js has the ability to run on the server side, which can result in Peer.js throwing errors when used with Next.js. One user on Stack Overflow explains this issue: The error is likely due to peer js performing side effects during import. The suggest ...

Pause the for loop until all nested asynchronous database calls are completed

Currently, I am utilizing the listCollection method within mongodb to loop through each collection that is returned using a query with find. The issue arises when I attempt to construct an object within the loop that I intend to return with response.json ...

Animating content with Jquery Waypoints for a seamless and elegant user experience

Currently tackling a project that requires some jQuery functions beyond my current skill set. Hoping to find some solutions here! The project in question is a one page scroll site, with existing jquery and waypoints functions implemented. Check out the c ...

Modify the values of an object by utilizing the setter function

How can I utilize the setter method to update existing values of an object and perform mathematical operations? var obj = { set model(object) { //method's logic } }; obj = {x:10, y: 20, p: 15}; obj = { x:10, y: 20, p: 15 set mod ...

Is there a way to automatically clear the text field value after submitting?

Greetings everyone, I'm looking for guidance on removing the text field content once I click submit. I have a button labeled "senden" and my goal is to clear the text fields and uncheck the checkbox after clicking this button. I've attempted se ...

The variable that was posted is not being successfully transferred within the query

There seems to be an issue with retrieving data from the ajax call in ajaxcall.php and assigning it to $place = $_POST['place']; in listplace.php. Despite this problem, the code runs smoothly otherwise. I've tried numerous times to get the ...

Jesting around with mocking console.error leads to test failures

The Issue: Currently, I am working on testing React components using Jest and Enzyme. In order to check for properties in development, I have incorporated the prop-types module. The prop-types module relies on console.error to alert when mandatory props a ...

Is MongoDB's find() method returning incorrect objects?

My current task involves running a Mongo query on the Order database to retrieve orders associated with a specific user by using their email. This process is achieved through an API, but I'm encountering difficulties as the returned object contains un ...

What are some ways I can customize the appearance of this Google Maps infoWindow?

I was able to create a Google Maps script using JavaScript code. The map displays multiple locations with corresponding latitude and longitude coordinates. This script can be viewed at . My objective now is to customize the appearance of the info windows ...