Having more than one controller for a single view in AngularJS

Is it possible to use multiple controllers for a single URL view in AngularJS? I am having trouble finding documentation on this. I want to have a controller that switches the page header title on all pages, but some pages already have a controller.

app.js

subscriptionApp.config(['$routeProvider',function($routeProvider){
$routeProvider.
when('/billinginfo',{templateUrl:'views/billing-info.html', controller:'billingInfoController'}).
when('/orderreview',{templateUrl:'views/order-review.html', controller:'billingInfoController'}).
when('/subscribed',{templateUrl:'views/subscribed.html', controller:'subscribedTitle'}).

//EXAMPLE: HOW COULD I ADD TWO CONTROLLERS TO SAME PAGE??? THIS DOES NOT WORK
when('/subscribe',{templateUrl:'views/subscribe.html', controller:'subscriptionController', 'testControllerTitle'}).

when('/unsubscribed',{templateUrl:'views/cancelconfirm.html', controller:'unsubscribedTitle'}).
when('/redirectBack',{templateUrl:'views/redirect-to-app.html'}).
when('/redirectHandler',{templateUrl:'views/redirect-handler.html',controller:'redirectController'}).
when('/error',{templateUrl:'views/error.html', controller:'messageController'}).
otherwise({redirectTo:'/subscribe'});
}]);

EDIT I am trying to add a title controller to each page view:

function testControllerTitle($rootScope, $scope, $http) { $rootScope.header = "Success!"; }

If I add these controllers to the pages that don't already have a controller, it works. However, if there is another controller in place, I can't make this work.

<h1 ng-bind="header"></h1>

Answer №1

Absolutely, controllers and templates work independently of each other. Take a look at this http://jsbin.com/abcdefg/2/

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

app.config( function ( $routeProvider ) {
  $routeProvider
  .when('/x', {templateUrl: 'this.html', controller: "xCtrl"})
  .when('/y', {templateUrl: 'this.html', controller: "yCtrl"})
  .when('/z', {templateUrl: 'that.html', controller: "zCtrl"})
  .otherwise({redirectTo: '/x'});
});

app.controller('xCtrl', function ($scope) {
    $scope.allItems = [1, 2, 3];
});

app.controller('yCtrl', function ($scope) {
    $scope.allItems = [4, 5, 6];
});

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

What is the best way to include ellipsis with a tally of remaining items in an Angular application?

Is it possible to display an ellipsis with the count of elements that are not fully visible within a given area? For example: Let's say we have an array of names: Apple, Mango, Straw, Litchi, Orange, Grapes Imagine our container is only 100px wid ...

I am experiencing issues with my JavaScript not functioning properly in conjunction with my HTML and CSS. I am uncertain about the root cause of the problem (The console is displaying an error message:

I am facing challenges in creating a content slider and encountering issues with its functionality. Specifically, when testing locally, I noticed that the current-slide fades out and back in upon clicking the arrows left or right, but the slide content is ...

Sending information into MySQL using NodeJS with the help of Postman

As a newcomer in the field, I am exploring how to combine MySQL with nodeJS for integrating projects into WordPress. app.post('/users/add', (req, res) => { id = req.body.id, firstname = req.body.firstname, surname = req.body.surname ...

What is the most effective way to programmatically select checkboxes based on array values in

Trying to keep it concise :) Working on a project that generates multiple pages of thumbnail images with checkboxes. The total thumbnails vary and are sorted into 1000 item html pages, called by a parent html page via iframe. Goal is for users to check che ...

Creating a prototype function in JavaScript

I am attempting to create a JavaScript prototype function that replicates the Python syntax of 'a' in 'abc'. The function works correctly in one example, but not in another. Can you help me identify what mistake I made? String.proto ...

Exploring an Array Based on User's Input with JavaScript

Looking to implement a search functionality for an array using AJAX. The array is pre-populated with values, and the user will input a value in a HTML text box. If the entered value is found in the array, it should display "Value found", otherwise "not f ...

If there are multiple instances of the component, it may not function properly

I have implemented a Vue component as shown below: <script setup lang="ts"> import { PropType } from "nuxt/dist/app/compat/capi"; interface Star { id: string; value: number; } const stars: Star[] = [ { id: &qu ...

Is it necessary for each React component to have its own individual stylesheet?

Looking for some advice on React as a newbie here. I'm wondering whether each React component should have its own stylesheet. For instance, if I have my main App component that gets rendered to the browser, is it sufficient to include a CSS file the ...

Is it possible to dynamically choose between GET and POST methods for an AJAX request?

Consider the following code snippet which intercepts the form submission event from two different forms. $("#aaa, #bbb").submit(function(e) { e.preventDefault(); var form = $(this); var url = form.attr('action'); $.ajax({ ...

Using Sequelize to send data from the client-side to the server-side

I am currently developing a project for a fictional library database and website interface. I am facing an issue where only 2 out of the 4 new loan form inputs are being passed to the req.body. Even though all items have a name attribute, it seems like onl ...

Exploring file serving in Node.js with passport authentications

I am currently utilizing Passport with the Google strategy for authentication. Here is my folder structure: views home.html enter.html (this contains just one Google+ button) app.js routes auth.js (handles Google login) I want the client to be direc ...

Can you explain the functionality of the NextSibling method?

I have a question about how the property NextSibling behaves when using the method getElementsByClassName(). Let me illustrate the issue with this code example: function Sibling() { var x = document.getElementsByClassName('firstClass')[0]; ...

Using a custom filter in AngularJS allows for seamless data filtering directly from the initial dataset

My goal is to implement a custom filter that will allow me to filter data based on a search word. The scope attribute gets populated in the controller's scope as shown below: naApp.controller('naCareNewTicketCtrl', ['$scope', &apo ...

PhpStorm 2019.2 introduces Material UI components that have optional props instead of being mandatory

My PhpStorm 2019.2 keeps showing me a notification that the Button component from Material UI needs to have an added href prop because it is required. However, when I refer to the Material UI API, I see something different. Take a look at this screenshot: ...

The error message "Each item within a list must be assigned a unique 'key' prop" is being displayed

At the moment, I'm immersed in a project that utilizes React, Next.js, and Ant-Design. However, during the development process, I encountered an error due to the absence of a unique key like so: Here's the detailed log of the error: Warning: Ea ...

angularjs unable to render included file

I am currently working on setting up a simple node-express angular application that involves using an ng-include directive. Here is the structure of my application: App: server.js package.json public: js css index.html partials: header.html partial-a ...

Explore the world of HTML event listening through .NET integration

Imagine this scenario: within an HTML page, using an UpdatePanel, you have a loading animated gif spinning while ASP.NET processes data from a webservice. I'm curious if there's a way to create an Event in .NET code that can be detected on the H ...

Merging RXJS observable outputs into a single result

In my database, I have two nodes set up: users: {user1: {uid: 'user1', name: "John"}, user2: {uid: 'user2', name: "Mario"}} homework: {user1: {homeworkAnswer: "Sample answer"}} Some users may or may not have homework assigned to them. ...

What could be the issue causing Vue to not start up properly?

I have been working on a Rails application and have integrated some Vue components into the pages. The components range from simple dynamic lists to more complex implementations with nested components. Let me walk you through how it all functions with som ...

Is the HTTP request from the browser being recorded?

When sending an HTTP request using fetch to website A from the Chrome console on website B, is it possible for website B to track any information about that request, or is it strictly client-side? In other words, can website B detect this action? Thank yo ...