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

What is the best way to transfer the value of a slider from jQuery or JavaScript to a Python Flask application

Trying to implement a round slider that displays its value on the client-side webpage. Whenever the user adjusts the slider, the updated value needs to be sent to the server using Python Flask as the backend. I attempted to achieve this using jQuery and Aj ...

Is it possible to prevent users from clicking on a jQuery UI Datepicker?

Is it possible to disable the functionality of a jQuery UI Datepicker so that clicking on it does nothing but display the date? I attempted: $("#calendar").datepicker({ disabled: true, altField: '#note_date', maxDate: 0 }); Unfortu ...

Is my jQuery code generating a large number of DOM objects?

I am currently developing a hex dumper in JavaScript to analyze the byte data of files provided by users. To properly display a preview of the file's data, I am utilizing methods to escape HTML characters as outlined in the highest-rated answer on thi ...

Troubleshooting: Angular ng-if not correctly detecting empty strings

When looking at my code, I have the following snippet to showcase data from angular scope variables. The initial two lines are functioning correctly and displaying data from the scope variables; however, there seems to be an issue with the line using ng- ...

The results generated by the Google Maps API are consistently consistent

const request = require('request'); var geocodeAddress = (location) => { var encodedLocation = encodeURIComponent(location); request({ url: `http://www.mapquestapi.com/geocoding/v1/address?key=APIKey&location=${encodedLocation}` ...

React: Why aren't class methods always running as expected?

I created a class component that retrieves a list of applications from an external API. It then sends a separate request for each application to check its status. The fetching of the applications works well, but there is an issue with the pinging process ...

When selecting a different file after initially choosing one, the Javascript file upload event will return e.target as null

Currently, I have implemented file uploading using <input>. However, when attempting to change the file after already selecting one, the website crashes and states that event.target is null. <Button label="Upload S3 File"> <input ...

An AngularJS-powered dynamic navbar

Apologies if my explanation is unclear, but I am struggling to find a simple way to convey the following information. I have set up a navigation bar that displays different categories of articles. These navigation items are pulled from a database and can ...

Decoding a JavaScript object when receiving it as JSON through a POST request

While browsing through various SO posts, I came across the statement "javascript is JSON". However, I am struggling to apply this concept in my application. My issue arises when I try to perform a POST request using jQuery. $.ajax({ type: &apo ...

Is there a way to deactivate the checkbox in an AngularJS input field?

<div ng-repeat="x in spaceutilization"> <input type="checkbox" name="{{x.filenumber}}" id="{{x.id}}" class = "pdffiles" value="101SP{{x.initials}}.dwg" /><label for="{{x.id}}"><button type = "button" class = "btn btn-primary btn-sm h ...

Achieving secure HTTPS connection with socket.io

At the moment, my setup involves: let connectTo = "http://myip:myport"; var socket = io.connect(connectTo, {secure: true}); on the client side and const port = myport; const io = require('socket.io')(port); on the server side. I am looking to ...

Developing Attributes in JSON

Greetings stackOverflow Community, I'm struggling a bit with creating JSON objects. I have code snippet that is meant to populate a list called members with names, and then add a property to each of those names. Here is the specific snippet in questi ...

The value of the bound variable in ng-options does not get updated after the array is

I have a situation where I am populating a list using an array and the ng-options directive in AngularJS. The selected item is bound to a variable called myObject.selectedItem. However, I noticed that even after clearing the array, the value of myObject.se ...

What is the process for inserting a scroll bar within a div element?

   I have recently created a webpage using some divs, along with a bit of CSS and JavaScript. I am struggling to figure out how to add a scrollbar to one of my divs. The code is not overly complex, as it includes both CSS and JavaScript. <html> & ...

AJAX request post parameters not recognized in ColdFusion form scope

I am currently developing a ColdFusion 8 training application that involves creating AJAX requests without using any libraries like jQuery. This is to support a basic CRUD application where data is retrieved and processed through various layers of the syst ...

Unable to execute a JavaScript function when triggered from an HTML form

This is the code for a text conversion tool in HTML: <html> <head> <title> Text Conversion Tool </title> <script type="text/javascript"> function testResults(form) { var str = form.stringn.value; var strArray = str.split(" ...

Utilizing React to connect with Metamask and share the signer across various contracts

I'm currently working on a solution for sharing signers across multiple JavaScript files. In my walletConnect.js file, I successfully connect to Metamask and retrieve an ERC20 token contract. async function connect(){ try{ const accounts = awai ...

Writing a CSV file to AWS S3 proves to be unsuccessful

I have been working with TypeScript code that successfully writes a CSV file to AWS S3 when running locally. However, I have recently encountered an error message: s3 upload error unsupported body payload object NOTES: The code is not passing creden ...

Caution: It is important for each child within a list to have a distinct "key" prop when using react-input

I'm currently facing an issue with the following code snippet: {array.map((item) => ( <> <input key={item.id} type="checkbox" /> ...

Guide on invoking an angular resource through a service

Currently I am utilizing Angular 1.1.5 (waiting for angular-ui-router to be compatible with version 1.2.0). Within my setup, I've defined a resource and service as shown below: myapp.factory( 'Monitoring', function($resource) { return $r ...