Assigning ng-view to "NAME" using RouteProvider

I'm completely new to Angular and I have a question regarding injecting a template or URL into multiple ng-views. However, my current approach involves having ng-view in my base template.

My base template structure is as follows:

<body>
   <div ng-view></div>
</body>

And this is how my JS looks:

var app = angular.module('myApp',[])
.config(['$routeProvider', '$locationProvider', '$httpProvider', function($routeProvider, $locationProvider, $httpProvider) {
    $routeProvider
    .when('/home', {
        templateUrl: '/contato'
    })
(...)

It works perfectly fine for loading a URL inside ng-view when there's only ONE ng-view scenario. But what if I need to load more than one ng-view? (e.g., ng-view="area1" and ng-view="area2")

I've attempted to define each ng-view in the $routeProvider, but it doesn't seem to work:

    $routeProvider
    .when('/home', {
        area1: {templateUrl: '/path1'},
        area2: {templateUrl: '/path2'}
})

What would be the correct way to set up individual templates for each ng-view separately?

Any assistance on this matter would be highly appreciated! Thank you.

Answer №1

Regrettably, it is not possible to have more than one ng-view on a single page. A recommended solution would be to explore UI-Router from AngularUI as it offers the functionality you seek (https://github.com/angular-ui/ui-router).

For reference, here is an example from their documentation (https://github.com/angular-ui/ui-router#multiple--named-views):

Setup:

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

HTML:

<body>
    <div ui-view="viewA"></div>
    <div ui-view="viewB"></div>
    <!-- Navigation links -->
    <a ui-sref="route1">Route 1</a>
    <a ui-sref="route2">Route 2</a>
</body>

Template 1:

<h1>State 1</h1>

Template 2:

<h1>State 2</h1>

JS:

myApp.config(function($stateProvider, $routeProvider) {

  $stateProvider
    .state('index', {
      url: "",
      views: {
        "viewA": { template: "index.viewA" },
        "viewB": { template: "index.viewB" }
      }
    })
    .state('route1', {
      url: "/route1",
      views: {
        "viewA": { templateUrl: "route1.viewA.html" },
        "viewB": { templateUrl: "route1.viewB.html" }
      }
    })
    .state('route2', {
      url: "/route2",
      views: {
        "viewA": { templateUrl: "route2.viewA.html" },
        "viewB": { templateUrl: "route2.viewB.html" }
      }
    });
});

You have the option to specify a controller at the state level that applies to both views, or at the view level for individual controllers.

Edit: Take a look at the live demo available in the ui-router docs (http://plnkr.co/edit/SDOcGS?p=preview)

Answer №2

Essentially, it is not possible to have two ng-view elements. Check out this question on Stack Overflow for more information:

You are limited to only one ng-view element.

However, you can modify its content in various ways: using ng-include, ng-switch, or by mapping different controllers and templates through the routeProvider.

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 tablesorter plugin from Jquery isn't functioning properly on my dynamically loaded ajax table

I am having trouble getting Tablesorter to work with my table. I attempted to use .trigger('update') but it did not have the desired effect for me. Instead, I tried using stupidtable and it worked to some extent, but not perfectly (it did not sor ...

Utilizing JSON with AJAX to dynamically fetch data on a separate webpage results in the page reloading despite implementing the e.preventDefault() method

Looking to retrieve a value on a new page and navigate without refreshing? I'm utilizing the POST method here along with JSON to fetch values. Still learning the ropes of this Ajax code! My goal is to move from the team.php controller page to team_d ...

The unexpected end of input error is caused by an Ajax call that returns a SyntaxError

I recently developed a basic notepad application where users can retrieve a specific file (which essentially translates to a row from MySQL) in order to make edits. When the form is submitted directly to the PHP file without preventing the default behavi ...

Passing a JavaScript Object to an ASP.NET Handler

How can I send a JavaScript object to an ASP.NET Handler and extract its values? I have defined a complex type object as follows: function AccountObjCreate() { var AccountsView = {}; AccountsView.Username = null; AccountsView.Email = null; AccountsView.P ...

Is it possible to simultaneously use the same plugin with various configurations and unique names in Vue?

I'm attempting to utilize the Vue Currency Input plugin, specifically with two different configurations simultaneously: import Vue from 'vue' import VueCurrencyInput from 'vue-currency-input' const options = { globalOptions: { ...

Verify ownership information by utilizing Node.js

Seeking guidance here. Currently, I am working on a Node.js and MongoDB application related to Apartment ownership. Within this application, there are two main datasets: Ownership and Tenants. For instance, Mr. A owns units 10 and 11. Then we have Mr. C wh ...

The client using socket.io is receiving events for "double plus one"

While experimenting with socketio, I encountered a bug that others are experiencing as well but I haven't been able to find a valid solution. This is the server-side code: const app = require('express')(); const server = require('http& ...

To view the contents of the dropdown list on an iPhone, simply tap the arrow key next to the mobile dropdown list and the contents will be

I am attempting to trigger the dropdown list contents to open/show by tapping on the arrow keys near AutoFill on the iPhone mobile keyboard. This action should mimic clicking on the dropdown itself. Currently, I am working on implementing this feature for ...

Issue with fs.createReadStream function: it is not recognized as a valid function

I'm currently developing a project in VUE that utilizes 'fs', and I have included my code below. async Upload(file){ let fs = require('fs'); console.log(file); console.log(this.dialogImageUrl); ...

Struggling with modifying class in HTML using JavaScript

I've been attempting to replicate a JavaScript code I came across on the internet in order to create a functioning dropdown menu. The concept is quite straightforward - the div class starts as xxx-closed and upon clicking, with the help of JavaScript, ...

Changing date and time into milliseconds within AngularJS

Today's date is: var timeFormat = 'dd MMM, yyyy hh:mm:ss a'; var todayDate = dateFormat(new Date(), timeFormat); Can we convert today's date to milliseconds using AngularJS? Alternatively, how can we use the JavaScript function getT ...

In JavaScript, creating a new array of objects by comparing two arrays of nested objects and selecting only the ones with different values

I've been struggling to make this work correctly. I have two arrays containing nested objects, arr1 and arr2. let arr1 =[{ id: 1, rideS: [ { id: 12, station: { id: 23, street: "A ...

What is the process for activating an event before another event on the same element with vanilla JavaScript?

Having an issue with the eventListener function. I am using the external library jquery.jstree-pre1.0fix2, which triggers a blur event on an input in my case. However, I need to trigger my event before the one from the library. I have come across some sol ...

Error: Attempting to access property of undefined variable

I have searched for similar titles related to my issue, but I still haven't found a solution. The error I am encountering when clicking on agent_dashboard on the side panel is as follows: txtDisplayName = <div style="border:1px solid #990000;paddi ...

Updating a database on ASP.NET without the need to refresh the page

We are developing a user-friendly application with ASP.NET MVC that focuses on uploading pictures and rating them. The app includes two voting buttons, "like" and "dislike". https://i.sstatic.net/Z3dp5.png Whenever the like button (green) is clicked, the ...

After zooming in on the canvas and panning, I encountered a problem where I was unable to drag objects within the canvas. Instead, the canvas continued to pan as I tried to move the objects

1) I have the ability to pan the canvas and drag images without scaling or zooming. 2) When scaling or zooming, I can still drag images within the canvas. 3) However, if I try to pan the canvas after zooming and then attempt to drag images, only the canv ...

Create an object with an asynchronous function/promise declaration

I have a function that returns an object with different functions that I can use. I want to incorporate promises into these functions for better asynchronous handling. var DATABASE = (function () { var exports = {}; exports.query = function(filter = ...

Animating the height in ng-show with AngularJS version 1.2

I'm attempting to implement a height animation with Angular JS 1.2. I have created a plunker that demonstrates the animation successfully for closing the item: http://plnkr.co/edit/YVtnXgjO3Evb6tz5DJOp?p=preview The crucial part of this implementati ...

What could possibly be causing my app to exhaust CPU resources on Mozilla Firefox?

I have created a unique game application for Facebook. Currently, the app is not optimized with AJAX technology, resulting in multiple server requests causing high CPU usage (specifically in Firefox) which slows down the overall performance of the app. Alt ...

Recalling the use of jquery toggle throughout the website?

I have successfully implemented a button to hide and unhide a lengthy menu with a click, but I am struggling to make the menu state persistent across multiple pages. I would like the last toggle action by the visitor to be remembered. Any suggestions on ho ...