The 'myCtrl' parameter is invalid as it is not recognized as a function and is currently set to undefined

I'm having trouble resolving this issue. I've implemented other controllers in the same manner that are working fine, but this specific one is throwing an error

Error: ng:areq Bad Argument"  "Argument 'myCtrl' is not a function, got undefined
. Below is my code:

//js
var myApp = angular.module('myApp', ['ngMaterial','angularUtils.directives.dirPagination']);

myApp.config(function($interpolateProvider) {
              $interpolateProvider.startSymbol('<@');
              $interpolateProvider.endSymbol('@>');
        });

(function(){

     var myContacts = angular.module('myApp');

     myContacts.controller('myCtrl', function ($scope, $http) {


            $scope.totalContacts = 0;
            $scope.request_limit = 3;

            $scope.pagination = {
                current: 1
            };

            getContacts(1); 

            $scope.pageChanged = function(newPage) {

                getContacts(newPage);
            };


            $scope.getContacts = function(pageNumber){

                api_url = '/api/people/list?page=' + pageNumber;


                $http.get(api_url).success(function(data){


                    $scope.contacts = data.data;
                    $scope.totalContacts = data.count

                    console.log('Data: '+ $scope.contacts);

                    if(data.code == 9999) {

                        displayMessage('Error', data.msg);

                    } else if (data.code == 8888) {

                        displayMessage('Error', data.msg);

                    } else if (data.code == 1001) {

                        displayMessage('Info', data.msg);

                    } else if (data.code == 1000) { 

                        $scope.contacts = data.data;
                        hideMessage();
                    }
                });
            }   
        });
})();

// html
<html lang="en" ng-app="myApp">
<head>...
 <div data-ng-controller="myCtrl"  class="container-fluid" id="pcont">
  <table class="table no-border hover">
   <thead class="no-border">
    <tr>
     <th class="text-center"><strong>Position</strong></th>
     <th class="text-center"><strong>Organization</strong></th>
    </tr>
   </thead>
   <tbody class="no-border-y">
    <tr dir-paginate="contact in contacts | itemsPerPage: request_limit" total-items="totalContacts"  current-page="pagination.current">
     <td class="text-center"><@ contact.contact_position @></td>
     <td class="text-center"><@ contact.organization_name @></td>
    </tr>
   </tbody> 
  </table> 

Can anyone spot what might be causing the error?

Answer №1

An issue may arise in your controller function due to the presence of this line, as the specified function is not defined:

getContacts(1);

This results in a failure to correctly define the controller, leading to the error generated by angular. Consider removing the aforementioned line and adding the following at the conclusion of your controller function instead:

$scope.getContacts(1);

Furthermore, it appears that a similar error exists within the $scope.pageChanged function. In order to rectify this, you should replace getContacts with $scope.getContacts.

Answer №2

Can you explain why the controller is wrapped in a function()? Maybe this alternative approach will help:

//js
var myApp = angular.module('myApp', ['ngMaterial','angularUtils.directives.dirPagination']);

myApp.config(function($interpolateProvider) {
              $interpolateProvider.startSymbol('{^');
              $interpolateProvider.endSymbol('^}');
        });

myApp.controller('myCtrl', function ($scope, $http) {


            $scope.totalItems = 0;
            $scope.limit = 3; // adjust based on API results per page

            $scope.pagination = {
                current: 1
            };

            getItems(1); 

            // Handle page change
            $scope.pageChanged = function(newPage) {

                getItems(newPage);
            };


            // Retrieve items 
            $scope.getItems = function(pageNumber){

                api_url = '/api/items/list?page=' + pageNumber;


                $http.get(api_url).success(function(data){


                    // Update scope data
                    $scope.items = data.data;
                    $scope.totalItems = data.count

                    console.log('Data: '+ $scope.items);

                    // Prepare message output
                    if(data.code == 9999) {

                        // Display error
                        showMessage('Error', data.msg);

                    } else if (data.code == 8888) {

                        // Show error
                        displayMessage('Error', data.msg);

                    } else if (data.code == 1001) {

                        // No data
                        // Display info
                        displayMessage('Info', data.msg);

                    } else if (data.code == 1000) { 

                        // OK, update scope
                        $scope.items = data.data;
                        hideMessage();
                    }
                });
            }   
        });

// html
<html lang="en" ng-app="myApp">
<head>...
 <div data-ng-controller="myCtrl"  class="container-fluid" id="pcont">
  <table class="table no-border hover">
   <thead class="no-border">
    <tr>
     <th class="text-center"><strong>Position</strong></th>
     <th class="text-center"><strong>Organization</strong></th>
    </tr>
   </thead>
   <tbody class="no-border-y">
    <tr dir-paginate="item in items | itemsPerPage: limit" total-items="totalItems"  current-page="pagination.current">
     <td class="text-center">{^ item.item_position ^}</td>
     <td class="text-center">{^ item.organization_name ^}</td>
    </tr>
   </tbody> 
  </table> 

Answer №3

I've reviewed your code and I'm having trouble identifying any errors due to its complex structure. However, I'll make an attempt to run it and see how it performs.

(function () {
    var myApp = angular.module('myApp', ['ngMaterial', 'angularUtils.directives.dirPagination']);

    myApp.config(function ($interpolateProvider) {
        $interpolateProvider.startSymbol('<@');
        $interpolateProvider.endSymbol('@>');
    });

    var myContacts = angular.module('myApp');

    myContacts.controller('myCtrl', function ($scope, $http) {

        $scope.totalContacts = 0;
        $scope.request_limit = 3;

        $scope.pagination = {
            current: 1
        };

        $scope.getContacts(1);

        // Handling page change
        $scope.pageChanged = function (newPage) {
            $scope.getContacts(newPage);
        };

        // Retrieving contacts
        $scope.getContacts = function (pageNumber) {

            api_url = '/api/people/list?page=' + pageNumber;

            $http.get(api_url).success(function (data) {
                $scope.contacts = data.data;
                $scope.totalContacts = data.count

                console.log('Data: ' + $scope.contacts);

                if (data.code == 9999) {
                    displayMessage('Error', data.msg);
                } else if (data.code == 8888) {
                    displayMessage('Error', data.msg);
                } else if (data.code == 1001) {
                    displayMessage('Info', data.msg);
                } else if (data.code == 1000) {
                    $scope.contacts = data.data;
                    hideMessage();
                }
            });
        }
    });
})();

Answer №4

Your explanation of the controller seems a bit unconventional. It's peculiar because your controller isn't integrated with your application from the start.

Here are two ways to implement a controller:

Method:1

var myApp = angular.module('myApp', ['ngMaterial','angularUtils.directives.dirPagination']);

myApp.config(function($interpolateProvider) {
$interpolateProvider.startSymbol('<@');
$interpolateProvider.endSymbol('@>');

});
myApp.controller('myCtrl', function ($scope, $http) {
// .. Remaining code for the controller

Refer to this guide for more information: Angular controller guide

Method: 2.

var myApp = angular.module('myApp',['ngMaterial','angularUtils.directives.dirPagination'])
.controller('myCtrl', myCtrl)

function myCtrl($location, common , config) {

}

Please follow John Papa's Angular conventions mentioned here John Papa Convention

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 script is not functioning properly due to an error stating "(Uncaught ReferenceError: $ajaxUtils is not defined)"

I'm having trouble figuring out what the issue is (Uncaught ReferenceError: $ajaxUtils is not defined) document.addEventListener("DOMContentLoaded", function (event) { showLoading("#main-content"); $ajaxUtils.sendGetReque ...

The power of RXJS's combineLatest operator

Upon using the combineLatest operator, I encountered an unexpected response when adjusting the interval duration of the first and second observables. Here is an example of the code: let intObs1$ = interval(1000).pipe(take(3)); let intObs2$ = interval( ...

There are currently no articles found that match the search query

Recently, I started working with Django, but I am facing an issue with slug. Whenever I send a request to the Slug, I encounter an error. The error message I receive is: Articles matching query does not exist. Furthermore, I am facing another error while ...

Combining Images and Navigation in Next.js using Tailwind CSS

I am facing an issue where the image from a particular section overlaps with the Navbar dropdown on mobile devices. Adding z-50 to the navbar did not solve the problem as expected. What I want is for the image to remain below the dropdown menu when it is ...

What is the best method for linking JavaScript to Python while exchanging data in JSON format bidirectionally?

I am currently exploring methods to establish a local connection between a Python server and a Javascript client by utilizing JSON format for the retrieval of data. Specifically, I aim to execute queries on the HTML client side, transmit these queries to t ...

An error occurred during the bundling process in React Native

I recently started using react-native and encountered a perplexing error that I cannot quite figure out. My goal is to integrate a calendar library into my project: https://github.com/wix/react-native-calendars I have added the necessary dependency for t ...

Issue with Ajax call not triggering the Controller Action in MVC

I am encountering an issue with making an ajax call to the controller action method that returns a json object. In addition, I need to pass the integer CheckID to the method. Any assistance would be greatly appreciated. Thank you in advance! ***View*** ...

What is the process for integrating a popup component into a React-Native application?

As a React-Native beginner, I wanted to incorporate a popup window into my app. After some research, I came across this solution: https://www.npmjs.com/package/react-native-popup I followed the first step: npm install react-native-popup --save However, w ...

Ways to implement a parallax effect by changing images within a specific div on scrolling with the mouse

First and foremost, thank you for taking the time to review my question. I am currently developing a website and I need to implement a vertical image transition effect within a selected division, similar to a parallax effect. Within this div, there are 3 ...

updating an object using its instance in angular: step-by-step guide

Having multiple nested arrays displaying data through HTML recursion in Angular, I am faced with the task of updating specific fields. Directly editing a field is simple and involves assigning its instance to a variable. arr=[{ "name":"f ...

Display temporary image until real image loads within ng-repeat angularjs

I am looking to display a placeholder image while the actual image is being loaded. I have tried using the ng-image-appear plugin. The issue I'm facing is that the placeholder image does not appear for img elements inside ng-repeat, although it works ...

Prompting the website to 'refresh' and return to the beginning of the page

My website's functionality is closely tied to the user's position on the page. Different features are triggered once specific distances are reached. I am seeking a way for users to automatically return to the top of the page upon page reload. Cu ...

Transforming an array of flat data into a hierarchical tree structure

I'm facing a challenge with my script. I have an Array of FlatObj and some rules, and I need to create a converter function that transforms them into TreeObj. The Rules are: If an object has a higher depth, it should be a child of an object with a l ...

Creating a unique kendo ui widget from scratch

Is there a way to create a custom widget that functions similarly to the example shown in this sample: http://jsfiddle.net/anilca/u2HF7/ I found some helpful information here, but I'm struggling with defining dropdownlist templates and linking them ...

How can MakeStyles be used to change the fill color in an SVG file by targeting specific IDs with Selectors?

Consider the following scenario: Contents of SVG file: <g transform="translate(...)" fill="#FFFFFF" id="Circle"> <path ........ ></path> </g> <g transform="translate(...)" fill="#FFFFFF" id="Circle"> &l ...

Ember controller failing to update template upon property set within promise execution

I am facing an issue while integrating user login functionality in my application. After retrieving the user data from the server, I aim to display the user's name on the page once the process is completed. The login form appears as a popup window, in ...

Encountered a failure while loading modules in AngularJS

When I tried opening the index.html page using Chrome, I encountered an error stating that the correct modules could not be found. Uncaught SyntaxError: Unexpected token < angular.js:1 Uncaught SyntaxError: Unexpected token < controller.js:1 ...

What are the steps to troubleshoot and fix the Internal Server Error on Next.Js?

I recently set up a new Next.js app using the command npx create-next-app. After that, I added Sass to my project with yarn add sass and proceeded to run it with yarn dev. To my surprise, I encountered multiple errors in both my terminal and on localhost. ...

What methods can be used by the client-side to determine whether a file has been successfully downloaded or received from

When a client-side file download request is initiated, I dynamically create a form element with hidden attributes and submit it to the server via POST. During this process, I need to display a loading spinner that will be hidden once the download is comple ...

Having trouble with sending a post request through ajax

Whenever I try to initiate an Ajax request upon clicking a button, the request never seems to get executed. Below is the snippet of my HTML code : <!DOCTYPE html> <html lang="en"> <head> <title>User Form</title> ...