Exploring Angular for Creating Single Page Applications

Within the past few days, I delved into Angular and decided that creating a simple single page application would be a great starting project. This endeavor aims to pave the way for a much larger project in the future.

I find myself grappling with understanding how pages (url locations) align with modules (reusable blocks with related controllers) on the page.

My initial approach was to define pages using a routing block like so:

var myApp = angular.module('myApp', ['ngRoute']);

myApp.config(function($routeProvider) {
    $routeProvider.
    when('/home', {
        templateUrl: 'home.html'
    }).
    when('/page2', {
        templateUrl: 'page2.html'
    }).
    otherwise({
       redirectTo: '/home'
    });
});

This routing block would reside in its own config.js file.

In addition, I envisioned having controllers tied to partials that could be reused across different pages.

For instance, let's consider a menu module that should appear on both the home and page2 pages.

I wanted this setup in a standalone file, similar to the following:

<div ng-controller="navMenu">
    <ul>
        <li>...
    </ul>
</div>

This structure allows me to organize my pages - such as home, page2, and others - in the following manner:

<ng-include src="/app/modules/menu.html"></ng-include>
<ng-include src="/app/modules/somethingElse.html"></ng-include>
<ng-include src="/app/modules/anotherThing.html"></ng-include>

Furthermore, my index.html body would look like this:

<ng-view></ng-view>

However, a roadblock emerged during implementation - the inability to dynamically load controllers. As a result, I would have to list out all possible controllers in one large file, contradicting one of Angular's key benefits.

Therefore, it appears that I may not have fully grasped Angular's concepts, prompting me to seek guidance. My goal is to have small reusable HTML blocks, each with its distinct controller, which can be loaded dynamically.

Many tutorials suggest assigning a controller to each page in the routing config, but given the shared functionality between pages, this approach seems redundant. Any assistance, resources, or ideas would be greatly appreciated. Thank you.

Answer №1

If I have correctly understood your query, it seems that using ng-include(d) for discrete chunks of functionality would be best implemented as directives.

With your route provider configuration, you can load the same controller for multiple pages by specifying the controller parameter in the object along with the templateUrl parameter. This enables you to share a controller across various partials, allowing for composability where you can mix and match partials with controllers depending on the route being served. However, this does require loading the controller scripts at startup rather than dynamically, which is the standard architecture approach for Angular solutions. If you do wish to load controllers dynamically, additional work is needed as demonstrated by Dan Wahlin in his article available here:

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

Change the position of a div by clicking a button using JavaScript

I have a div with an image that I want to move by clicking on a button within the same div. The reason for this is that clicking on the image itself allows it to move inside the div, but I want another element to control the movement of the entire div. He ...

Efficiently handling multiple form submissions using a single jQuery Ajax request

I'm working on a page that has 3-4 forms within divs, and I want to submit them all with just one script. Additionally, I want to refresh the content of the specific div where the form is located. However, I'm unsure of how to specify the current ...

Delay in changing the z-index of FloatingActionButton on hover

In my current issue, I am facing a problem where a div that is meant to always stay below a FloatingActionButton (FAB) ends up temporarily appearing above it when z-index values are changed. The scenario is such that upon clicking the FAB, an invisible ove ...

Query key array failing to update when key is modified

Encountering an issue with the query key array not updating when the selected warehouse ID is changed. This causes useQuery to use outdated data instead of fetching new data for the updated warehouse ID. Struggling to figure out how to update the query k ...

establish the data type for the key values when using Object.entries in TypeScript

Task Description: I have a set of different areas that need to undergo processing based on their type using the function areaProcessor. Specifically, only areas classified as 'toCreate' or 'toRemove' should be processed. type AreaType ...

Undefined method error encountered within Vue.js nested ref structure

My component structure is three levels deep and it's set up like this: - container - section-1 // section1Ref - form-1 // form1Ref The submit method in the container component will call the submit method in section-1 using this.$refs.section1R ...

Vue.js: Incorporating a client-side restful router using vue-router and a state manager

Trying to set up a client-side restful api with vue.js and vue-router where route params can be utilized to showcase a subset of a store's data into components. All the necessary data for the client is loaded into the store during initialization (not ...

In what ways can I incorporate Django template tags into my JavaScript code?

I've encountered an issue with implementing my model data into a FullCalendar library template in JavaScript. Despite seeing others do the same successfully, I keep getting errors as the template tags fail to register properly. <script> documen ...

What is the best way to extract value from a JSON object with jQuery?

How can I retrieve the value of 'FRI' from the JSON feed returned by an AJAX call using jQuery? $.ajax({ url: query, type: "GET", dataType: "json" success: function(data) { var day = // extract data value from JSON ...

What is the process for updating button text upon clicking in Angular?

To toggle the text based on whether this.isDisabled is set to false or true, you can implement a function that changes it when the button is clicked. I attempted to use this.btn.value, but encountered an error. import { Component } from '@angular/core ...

Is the functionality compatible with all browsers even though <div /> is not recognized as a proper HTML element?

Can the code $("<div />").appendTo($mySelector) be relied upon for safety and cross-browser compatibility, considering that <div /> is not a valid HTML element? I pose this question because it seems much simpler to use than $("<div><d ...

Having trouble with the "Cannot POST /public/ error" when converting a jQuery ajax call to vanilla JavaScript

Following up on a question from yesterday (Update HTML input value in node.js without changing pages), my goal is to submit an HTML form, send an ajax request to the server for two numbers, perform an addition operation on the server, and display the resul ...

Dealing with performance issues in React Recharts when rendering a large amount of data

My Recharts use case involves rendering over 20,000 data points, which is causing a blocking render: https://codesandbox.io/s/recharts-render-blocking-2k1eh?file=/src/App.tsx (Check out the CodeSandbox with a small pulse animation to visualize the blocki ...

I am experiencing an issue where the Axios configuration does not display the OnUploadProgress on my response

I have been attempting to track the progress of file uploads from the front end, but I am encountering an issue where the onUploadProgress is not being received in the configuration catch. This problem arises as I am relatively new to using Axios. axios({ ...

Adding a JSON array to all JSON objects in JavaScript: A step-by-step guide

Here is a JSON Object that I am working with: { "status": "CREATED", "overrides": { "name": "test_override" }, "package_name": "test", "name": "app1", "defaults": { "job": { "example": { "executors_num": "2", "fr ...

Combining column headers in ng-table with AngularJS

Trying to merge columns with ng-table I've been attempting to merge table headers with ng-table, After searching through ng-table's documentation, I couldn't find anything, I came across the html attribute 'columnspan', but my g ...

Issues with fundamental JavaScript client-side code

As a newcomer to the world of javascript and jQuery, I am diving into my first experiment with javascript. My initial focus has been on changing questions by clicking next or previous buttons. The goal is to create a dynamic quiz webpage that updates quest ...

What is the proper way to utilize props.theme.breakpoints in conjunction with the makeStyles hooks?

Can anyone help me understand how to incorporate the Material breakpoints provided at https://material-ui.com/customization/breakpoints/ into the makeStyles hook for responsive styling? I am having trouble using props.breakpoints.down('600') with ...

Show various forms that gather information

Upon selecting an option from the drop-down menu, a certain number of forms will be displayed with captured data. For example: Imagine owning a form with fields such as No. of Applicants, Applicant Name, Telephone, E-mail, etc... If the user selects 2 fo ...

Utilizing the power of $.ajax() to parse through an XML document

I have a query about working with a large XML file containing 1000 nodes. Here is the code snippet I am using: $.ajax({ type: "GET", cache: false, url: "someFile.xml", ...