An example of ngRoute demonstrating the functionality of multiple controllers

I am currently working on a small ngRoute example to incorporate multiple applications and controllers. The first app/controller is for the main page, while the second set of app/controllers is for the HTML that ngRoute loads after pressing a button. However, I seem to be encountering some issues with it not functioning as expected. See the code snippet below:

Main Module

var app = angular.module("MainModule", ["ngRoute"]);

Main Controller

app.controller("MainController", function ($scope) {

});

app.config(function ($routeProvider) {
    $routeProvider
        .when('/customers', {
            templateUrl: "customers.html",
            controller: "CustomerController"
    })
});

Customer Module

var CustomerModule = angular.module("CustomerModule", []);

Customer Controller

CustomerModule.controller("CustomerController", function ($scope) {

$scope.Test = "Hey";

$scope.CustomerArray = [
    { "firstName" : "John", "lastName" : "Williams", "Occupation" : "Fireman"     },
    { "firstName" : "Louis", "lastName" : "Abrams", "Occupation" : "Policeman" }
    ]   
});

index.html

<!DOCTYPE html>
<html>
<head>
    <title></title>
    <meta charset="utf-8" />

    <script src="http://ajax.googleapis.com/ajax/libs/angularjs/1.4.8/angular.min.js"></script>
    <script src="http://ajax.googleapis.com/ajax/libs/angularjs/1.4.8/angular-route.js"></script>
    <script src="scripts/MainModule.js"></script>
    <script src="scripts/MainController.js"></script>
    <link rel="stylesheet" type="text/css" href="MyCSS.css">
</head>
<body>


    <div ng-app="MainModule">
        <div id="TopDiv">Main Module</div>
        <a href="#/customers"><input type="button" value="Load Customers" /> </a>

        <div ng-view></div>

    </div>

</body>
</html>

customers.html

<!DOCTYPE html>
<html>
<head>
    <title></title>
    <meta charset="utf-8" />

    <script src="http://ajax.googleapis.com/ajax/libs/angularjs/1.4.8/angular.min.js"></script>

    <script src="scripts/CustomerModule.js"></script>
    <script src="scripts/CustomerController.js"></script>
</head>
<body>
    <div ng-app="CustomerModule" ng-controller="CustomerController">
        {{Test}}

            <ul>
                <li ng-repeat="x in CustomerArray">{{x.firstName x.lastName x.Occupation}}</li>
            </ul>

    </div>
</body>
</html>

The output when I press the "Load Customer" button shows {{Test}} with no array data visible. As a new learner of Angular, any assistance with this issue would be greatly appreciated. I am exploring this for learning purposes and welcome any guidance or advice. Thank you!

Answer №1

I have created a functional example by building upon the code provided in the original question. Several adjustments were implemented, and I will outline each modification with some explanation.

While it is not mandatory for each "page" to possess its own module, it can be considered a good practice. To accommodate the structure of one module per view as presented here, the following changes were made:

Add the CustomerModule as a dependency in the MainModule (MainModule.js):

var app = angular.module("MainModule", ["ngRoute", "CustomerModule"]);

Ensure ALL scripts are loaded in the index.html:

<script src="scripts/MainModule.js"></script>
<script src="scripts/MainController.js"></script>

<script src="scripts/CustomerModule.js"></script>
<script src="scripts/CustomerController.js"></script>

By making these adjustments, the $routeProvider can find the CustomerController and activate it when a route is changed. The customers.html file no longer needs to define a controller and can instead function as a complete partial. Additionally, the expression used in customers.html had to be revised and separated into distinct expressions for each property.

The updated customers.html looks like this:

{{Test}}

<ul>
  <li ng-repeat="x in CustomerArray">{{x.firstName}} {{x.lastName}} {{x.Occupation}}</li>
</ul>

You can access the fully functional sample on plnkr.co: http://plnkr.co/edit/EjwW9Fsc2DPhBejUETwB?p=preview

Answer №2

It seems like the issue lies within your MainModule code. It should look something like this:

var app = angular.module("MainModule", ["ngRoute"]);

When you use angular.module with only one parameter, it's just fetching the module and not creating a new one.

Your customers.html file should only contain parts of your HTML, not the entire document:

Here is a snippet from customers.html


{{Test}}

<ul>
    <li ng-repeat="x in CustomerArray">{{ x.firstName }} {{ x.lastName }} {{ x.Occupation }}</li>
</ul>

Make sure to include your customer JS files in the index.html:


<script src="scripts/MainModule.js"></script>
<script src="scripts/MainController.js"></script>
<script src="scripts/CustomerModule.js"></script>
<script src="scripts/CustomerController.js"></script>
<link rel="stylesheet" type="text/css" href="MyCSS.css">

I hope this information helps resolve the issue.

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

Preserve StepContent information within Material-ui Stepper during updates to the active step

I have a Stepper component with multiple steps, each containing several TextFields. The issue is that material-ui unmounts the step contents when you switch steps, causing all the data in the TextFields to be lost. My question is: Is there a way to prese ...

Retrieve a JSP list item using JavaScript

In my setup, I have a Servlet, JSP page, and JavaScript. I pass a list from the servlet to the JSP, where it displays the results. Each result is shown in a table and includes a delete button. My goal is to retrieve the ID of the result I want to delete an ...

the display outcome appears fuzzy and lacks sharpness

Currently, I am engaged in prototyping and showcasing data in a 3D format using three.js (version 68). The intended outcome of the entire animation is to have a collection of colored spheres representing protons and neutrons, each colored based on a specif ...

Troubleshooting jQuery's issue with dynamically adding input fields

I came across a tutorial (which I tweaked slightly) on this website: code In JSFiddle, everything works perfectly fine with the code. However, when I implemented it on my actual page, it's not functioning as expected. I've been trying to trouble ...

Is there a way to include input text along with a file upload in an AJAX request to upload.php? And how exactly would I go

How do I include the book name entered in the form field with id:bname in the request to be sent to the page upload.php, and how can I retrieve this text on the upload.php page? function uploadFile(){ var file = document.getElementById("upload"). ...

How to effectively pass data between parent and child controllers in Angular 1 - Seeking guidance

Currently, I am working on two separate applications that have a common requirement of displaying active incidents and closed incidents. Both apps involve similar logic for creating, modifying, saving, and deleting incidents. I am exploring the best appro ...

Connecting radio buttons to data in Vue using render/createElement

How do you connect the value of a selected radio button to a specific variable in the data object within a Vue application when using the render/createElement function? ...

Redux Form: Input remains untouched with `touched: false'

Looking to validate my input fields and dynamically change the CSS based on user interaction. To start, I implemented a required validation method by wrapping all input components with a <Field> tag and passing an array of functions to the validate ...

Jquery on method triggers a single event only

I am encountering an issue with adding and removing a class from an element using the on() method to handle click events. The code works fine on the first click, but subsequent clicks do not trigger the event anymore. Here is the code snippet: $(&apo ...

Tips for creating an infinite repeating loop in jQuery

I'm attempting to create a jQuery infinite loop featuring images within a div. I've experimented with using the setInterval function, but encountered an issue where the animation starts after a 3-second delay and does not seamlessly repeat itself ...

Tips for accessing elements using document.getElementsByTagName

Greetings and best wishes for the holiday season! I hope everyone is cozy and safe. I need a little help with some code here, as I am fairly new to JavaScript but not entirely new to programming. Despite finding an answer on this site, I am still encounter ...

What is the method for retrieving data from the root component within a child template in VueJs?

How can I access this.$root from within a VueJs template? For example: <template> <v-card elevation="this.$root.$refs.foo.cardElevation"> Foo </v-card> </template> I am aware that I can create a data property and ...

Using jquery to submit a form with multiple fields spread across various tabs

Utilizing a bootstrap modal, I aim to display detailed information about a single product. Within this modal, there are three tabs categorized as details, image, and specification for the respective content components of the product. Upon clicking the edi ...

Managing two variables in C# Controller and View

I am facing an issue with the two variables in my controller class. The first variable, currentUserId, is supposed to store the user currently logged into the website. The second variable, currentRoomId, should track the chat room the user is in. The probl ...

Trouble with passing options to ES6 module imports

After coming across this Stackoverflow thread, I am attempting to pass options to ES6 imports. Initially, this code worked without any issues: export default (Param1:any, Param2:any) => { return class Foo { constructor() { cons ...

Calling Ajax to Flask for fetching MySQL query results

My goal is to populate a drop-down list in my HTML using AJAX by calling my flask app app.py from app.js. I am attempting to load the data when the page initially loads and triggering the AJAX within $(document).ready as shown below: Here is the content o ...

Failure to update HTML with AJAX request

I am currently working on a form that calculates shipping costs based on the user's postcode input. The process involves retrieving the user's text input of the postcode, fetching the shipping cost for that specific postcode using PHP, and then u ...

Encountering an unforeseen change in the "buttonText" attribute

I've developed a simple Vue.js component for a button. When the button is clicked, it should display the text "I have been clicked." It does work as expected, but I'm also encountering an error that reads: 49:7 error Unexpected mutation of "but ...

broker handling numerous ajax requests simultaneously

Is there a way to efficiently handle multiple simultaneous ajax calls and trigger a callback only after all of them have completed? Are there any JavaScript libraries available that can manage numerous ajax calls to a database at the same time and execute ...

JavaScript: Append an ellipsis to strings longer than 50 characters

Can the ternary operator be utilized to append '...' if a string surpasses 50 characters? I attempted this approach, however it did not work as expected. {post.title.substring(0, 50) + post.title.length > 50 ? '...&ap ...