The functionality 'PeopleController' does not appear to be defined and is generating an undefined error in IonicJS

  1. Utilizing IonicJS to display JSON data.
  2. Encountering an error: "Argument 'PeopleController' is not a function, got undefined" I have verified the file people_controller.js

(function() { var app = angular.module('peopleController',[]);

app.controller('PeopleController',
    function($scope, $http) {
    var url = 'http://localhost:3000/api/people';
    $http.get(url)
    .success(function(people) {
    $scope.people = people;
    })
    .error(function(data) {
    console.log('server side error occurred.'); 
    }); 
    } 
    );
    }); 

app.js:

angular.module('starter', ['ionic', 'peopleController'])

.run(function($ionicPlatform) {
  $ionicPlatform.ready(function() {
    if(window.cordova && window.cordova.plugins.Keyboard) {
      // Hide the accessory bar by default (remove this to show the accessory bar above the keyboard
      // for form inputs)
      cordova.plugins.Keyboard.hideKeyboardAccessoryBar(true);

      // Do not remove this line unless you know what you are doing. It stops the viewport
      // from snapping when text inputs are focused. Ionic handles this internally for
      // a much nicer keyboard experience.
      cordova.plugins.Keyboard.disableScroll(true);
    }
    if(window.StatusBar) {
      StatusBar.styleDefault();
    }
  });
})

index.html:

<!DOCTYPE html>
<html>
  <head>
    <meta charset="utf-8">
    <meta name="viewport" content="initial-scale=1, maximum-scale=1, user-scalable=no, width=device-width">
    <title></title>

    <link href="lib/ionic/css/ionic.css" rel="stylesheet">
    <link href="css/style.css" rel="stylesheet">

    <!-- IF using Sass (run gulp sass first), then uncomment below and remove the CSS includes above
    <link href="css/ionic.app.css" rel="stylesheet">
    -->

    <!-- ionic/angularjs js -->
    <script src="lib/ionic/js/ionic.bundle.js"></script>


    <!-- cordova script (this will be a 404 during development) -->
    <script src="cordova.js"></script>

    <!-- your app's js -->
    <script src="js/app.js"></script>
  </head>
   <body ng-app="starter">

    <ion-pane>
      <ion-header-bar class="bar-stable">
        <h1 class="title">Ionic Blank Starter</h1>
      </ion-header-bar>
      <ion-content>
      <ul class="list" ng-controller="PeopleController">
<li class="item" ng-repeat="person in people">
<h3>{{person.name}}</h3>

</li>
</ul>

      </ion-content>
    </ion-pane>
     <script src="../js/controllers/people_controller.js"></script>

  </body>
</html>

Where am I Going Wrong?

Answer №1

Ensure the PeopleController module is injected after it has been compiled/inserted into your application. Verify the sequence of JS files by loading PeopleController.js before app.js

Answer №2

To solve the issue, you must eliminate peopleController from the list of module dependencies in the code

angular.module('starter', ['ionic'])
.

Remember that a controller is not the same as a module.

Here's how to make the necessary changes:

Replace

app.controller('PeopleController',...)
with
angular.module('starter').controller('PeopleController',...)

Don't forget to include the Angular files and the PeopleController.js file:

<!-- Include your app's JavaScript -->
<script src="angular/angular.min.js"></script>
<!-- Make sure to include Ionic Dependencies -->
<script src="js/app.js"></script>
<script src="js/PeopleController.js"></script>

Answer №3

One issue that was causing trouble was the ordering of JS files. Initially tried loading the app.js file after the peopleController.js with no success.

After rearranging and loading app.js right after peopleController.js, everything worked perfectly.

  <script src="js/app.js"></script>
  <script src="js/controllers/people_controller.js"></script> 

Updated Project Structure:

index.html

 <!DOCTYPE html>
    <html>
      <head>
        <meta charset="utf-8">
        <meta name="viewport" content="initial-scale=1, maximum-scale=1, user-scalable=no, width=device-width">
        <title></title>

        <link href="lib/ionic/css/ionic.css" rel="stylesheet">
        <link href="css/style.css" rel="stylesheet">

        <!-- IF using Sass (run gulp sass first), then uncomment below and remove the CSS includes above
        <link href="css/ionic.app.css" rel="stylesheet">
        -->

        <!-- ionic/angularjs js -->


        <script src="lib/ionic/js/ionic.bundle.js"></script>


        <!-- cordova script (this will be a 404 during development) -->
        <script src="cordova.js"></script>

        <!-- your app's js -->
        <script src="js/app.js"></script>
          <script src="js/controllers/people_controller.js"></script>
      </head>
       <body ng-app="starter">

        <ion-pane>
          <ion-header-bar class="bar-stable">
            <h1 class="title">Ionic Blank Starter</h1>
          </ion-header-bar>
          <ion-content>
          <ul class="list" ng-controller="PeopleController">
    <li class="item" ng-repeat="person in people">
    <h3>{{person.name}}</h3>

    </li>
    </ul>

          </ion-content>
        </ion-pane>

      </body>
    </html>

app.js

angular.module('starter', ['ionic', 'peopleController'])

.run(function($ionicPlatform) {
  $ionicPlatform.ready(function() {
    if(window.cordova && window.cordova.plugins.Keyboard) {
      // Hide the accessory bar by default (remove this to show the accessory bar above the keyboard
      // for form inputs)
      cordova.plugins.Keyboard.hideKeyboardAccessoryBar(true);

      // Don't remove this line unless you know what you are doing. It stops the viewport
      // from snapping when text inputs are focused. Ionic handles this internally for
      // a much nicer keyboard experience.
      cordova.plugins.Keyboard.disableScroll(true);
    }
    if(window.StatusBar) {
      StatusBar.styleDefault();
    }
  });
})

peopleController.js:

(function() {
var app = angular.module('peopleController', []);

app.controller('PeopleController',
function($scope, $http) {
var url = 'http://localhost:3000/api/people';
$http.get(url)
.success(function(people) {
$scope.people = people;
})
.error(function(data) {
console.log('server side error occurred.'); 
}); 
} 
);
})(); 

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

Triggering successive jQuery confirm boxes once the previous one has finished processing

I am facing an issue with my API call response where I receive an array and need to open jQuery Confirm one by one for each item in the response. The problem is that they all open at once. Below is the code snippet: axios.post('/orders/ask-for-or ...

Next.js version 13 is causing the page to refresh each time the router is pushed

I am currently developing a search application using NextJs 13, and I have encountered an issue where the page refreshes every time I click the search button. Strangely, this only happens when the application is deployed on Vercel. When running the app l ...

Executing Directive function from Controller in AngularJS with or without passing parameters

I have been searching extensively on the Internet, but I have not come across any good examples that fit what I'm looking for. This could be because I am new to AngularJS. What I need is a way to execute some common functions in different situations ...

Retrieving a collection of data from MongoDB featuring today's date

How can I retrieve a list of items from MongoDB with today's date dynamically instead of hardcoding the date in my pushups.js file like "date":"2017-10-26T07:09:36.417Z? Take a look at the code snippet below: Here are the documents in my MongoDB: { ...

A method of iteration that allows us to traverse through an object, regardless of whether it contains a single item or an array of items, is known as dynamic looping

I am dealing with a JSON output that can have different types of data: There may be an array of objects like this: var data = { "EARNINGS": [ { "PAYMENT": "1923.08", ...

I'm struggling to grasp the concept of map-reduce in MongoDB and it's leaving me feeling lost and

I'm currently exploring the potential of map-reduce in order to better grasp its utility. Within my database, I have a collection titled "actions" containing 100k documents structured like this: { "profile_id":1111, "action_id":2222 } My ai ...

React NextJS: Unable to retrieve cookies or properties post redirection

Within my nextJS application, when a user logs in on the login page, a cookie is created with a token and then they are redirected to the main page which utilizes the main component. However, within the Main component, I am encountering an issue where the ...

Unable to successfully register a ServiceWorker due to an unsupported MIME type ('text/html') in Vue.js

I have successfully implemented a service worker in my Vue.js project before with simple HTML projects, where it worked great. However, when I include the same file in my Vue.js code, it keeps throwing an error: The script has an unsupported MIME type ( ...

Dynamic Drop Down Menu with PHP and AJAX loading data from a JSON

Struggling to establish a connection between two drop-down menus using AJAX with data in JSON format. Despite multiple attempts, the code only displays empty drop-downs for both departments and projects. Unsure of where the mistake lies. Here is the code ...

Using AngularJS to chain promises

After coming across some advice on AngularJS validation and promises, I am interested in creating a chain of confirmation dialogs to validate multiple steps at once. By making an API call based on user input, we can determine what steps require confirmati ...

Guide to dividing by pipe for multiple selection in a concealed domain

My form consists of 3 drop down menus for user selections. The first menu allows users to choose a specific Type, the second menu requires them to select a date which then filters options in the third drop down using Jquery. Initially, the setup allowed us ...

Adding JSON objects to an array using Javascript and Jquery

I am working with a JSON object that is returned from a $.post in jQuery. I want to store this data client-side by adding it to an array and continuously appending the array as new search results come in. This is the JSON data: { "companies": [ { "comp ...

Creating a dynamic CSS height for a div in Angular CLI V12 with variables

Exploring Angular development is a new venture for me, and I could use some guidance on how to achieve a variable CSS height in Angular CLI V12. Let me simplify my query by presenting it as follows: I have three boxes displayed below. Visual representatio ...

How can I compare two fields in a MongoDb query when one of them is an ObjectId?

For my Interactive platform, I have chosen MongoDB as the database. My requirement is that only the blog owner who is signed in should be able to delete the blog. However, there seems to be a loophole where this criteria can be bypassed using another user& ...

Create a new object by mapping values from an array of two objects in Angular using TypeScript, based on the object

Here is a code snippet for a Question and Answer data structure: export class Question { id: string; title: string; description: string; answers: Answer[]; } export class Answer { id: string; text: string; questionId: string; } We have two ...

What is the best way to obtain an array format in JavaScript?

In AngularJs, I am retrieving an array using a factory function. This is the console output: Array[0] 0: "value1" 1: "value2" length:2 However, when I try to get the length of the array: console.log(array.length) I am fetching data from MySQL in ...

The double click feature is not functioning properly when used in conjunction with the selectpicker Boostrap

<select class= "selectpicker" id="cus_id"> <option value="654" >test1</option> <option value="6877" >test2</option> <option value="8687" >test3</option> </select ...

Is it possible that the document is corrupted since it is not updating and no error is being displayed?

I am encountering an issue where one specific document does not update, although the same query successfully updates any other _id that I query: Category.findOneAndUpdate( {_id : req.params.id}, {parent : req.body.parent}, function(err,obj){ ...

displaying outcomes as 'Indefinite' rather than the anticipated result in the input field

I need to automatically populate values into 4 text fields based on the input value entered by the user. When the user exits the input field, a function called getcredentials() is triggered. This function, in turn, executes Python code that retrieves the r ...

Using JavaScript to capture patterns with regex

Beginning my journey in automation! I am using wdio5, cucumber, and selenium framework with gherkin language. My task is to create a step file in JavaScript for a gherkin feature that includes these examples: Examples 52.27 .27 2.27 I hope I phrased my ...