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

Transferring user inputs to the server through jQuery-AJAX

I've encountered some issues when trying to send form data inputs to the server. Despite alerting each form input, I keep getting empty alerts. Here's my code snippet: With my current code, it only alerts 0. However, posting normally seems to wor ...

Are we retrieving multiple APIs the right way?

Looking for some guidance on fetching two APIs in React. I have created two functions to handle this task and called them simultaneously within another function. Should I stick with this approach or move the API calls to componentDidMount? Additionally, I& ...

Properly configuring the root directory to troubleshoot Axios 404 POST issues within a Vue Component coupled with Laravel

As I delve into learning Vue+Laravel through a tutorial, I have encountered an issue with Axios when making an Ajax request within the script of a Vue Component. The console log error that is troubling me reads as follows: POST http://localhost/favori ...

Using Regular Expressions to eliminate any characters that are not directly adjacent to numbers (beside specific characters)

My function generates a result that looks like this: given output For comparison, consider the example string below: var string = '    111   1   1\n 1111111 1 \n   &nb ...

Issue with OnClientClick functionality not functioning as expected

I am having trouble with the validation function that is supposed to be triggered when clicking on the back and next buttons in my code. For some reason, the OnClientClick validation function is not being called when I click on the buttons. Can anyone pro ...

The rule 'react-hooks/exhaustive-deps' does not have a defined definition

I received an eslint error message after inserting // eslint-disable-next-line react-hooks/exhaustive-deps into my code. 8:14 error Rule 'react-hooks/exhaustive-deps' definition not found I tried to resolve this issue by referring to this p ...

Removing background color and opacity with JavaScript

Is there a way to eliminate the background-color and opacity attributes using JavaScript exclusively (without relying on jQuery)? I attempted the following: document.getElementById('darkOverlay').style.removeProperty("background-color"); docume ...

Is there a way to execute v-for once the created() lifecycle hook has finished running?

In my current project, I am faced with the challenge of including avatars in notifications. Despite my efforts, I have not been able to solve this issue independently. The Vue.js template below demonstrates how I have attempted to add avatars to each notif ...

Issues arise when attempting to transfer strings through ajax to a Node.js server that is utilizing express.js

On my website, I am encountering a problem where certain characters are being lost when I send strings to my Node.js server. // Client: microAjax("/foo?test="+encodeURI("this is ++ a test"), function callback(){}); // Server: app.get('/foo',fun ...

I am facing an issue where the module pattern functions perfectly on JSBin, but fails to work properly

As a backend developer, I typically only write JavaScript when absolutely necessary, and not always in the best way. However, I have decided to turn over a new leaf and start writing more organized code that follows best practices as much as possible. To ...

Filtering in AngularJS can be performed by checking if a value in a specific key of one array is also present as a value in a specific

This query was originally posted on this thread I am looking to implement a filter that will display the values of colors.name only if they also exist in cars.color $scope.colors = [{"name":"blue","count":2}, {"name":"red","count":12}, ...

Moving a function from the controller to the directive

After examining my angular controller, I realized that it is expanding and should ideally focus on passing data. Currently, there is a function within my controller that calculates the number of months' worth of data displayed (within a 12-month peri ...

Strategies for handling numerous node projects efficiently?

Currently, we are utilizing three distinct node projects: Project 1, Project 2, and Project 3 incorporating react and webpack. Each of these projects is stored in their individual repositories. While Project 1 and Project 2 operate independently, Project ...

Using querySelector() to target specific divs by their classes while excluding any other classes

I am attempting to retrieve only the first divs while excluding the second ones: <div class="_5pcr userContentWrapper"> <div class="_5pcr userContentWrapper _4nef"> After researching, I discovered that the querySelector function should be abl ...

How can I access the object that created an interval from inside an interval callback function?

I am facing a challenge with JavaScript as a beginner. I am working on a React App and trying to add a timer feature to it. I have successfully created the timer functionality, but the issue lies in the timer callback (similar to this query: setInterval in ...

The utilization of "startIcon" and "endIcon" from the <Button/> API of Material-UI is restricted

I've been trying to work with this React code for a single component, but no matter what I do, I keep getting the same warning. I even tried copying and pasting the example, but the warning persists and the icon is not showing up. Can someone please a ...

NodeJS - The function app.listen is not defined in this context

I've come across a similar question before, but the answers provided didn't help me resolve my issue. The error message I'm getting is "TypeError: app.listen is not a function"; Here's my full code below. Thank you in advance for your ...

Convert data in JavaScript and send it as a string in PHP

I'm currently facing a small issue with my JavaScript code. Specifically, I am using AJAX and attempting to retrieve a variable in PHP. Everything seems to be working fine except for the "param" data. Below is the snippet of my code: $('#sign ...

Iframe not displaying Base64 encoded PDF in Chrome App

Currently, I am in the process of developing a Chrome App that essentially acts as a wrapper for the main app within a webview. The webview sends a Base64 encoded PDF as a message to the app, which then creates a hidden iframe and loads the PDF into the fr ...

I'm trying to access my navigation bar, but for some reason, it's not allowing me to do so

Having trouble getting the navigation bar to open. I have set it up so that when clicked, it should remove the hide-links tag, but for some reason, it does not toggle properly and keeps the ul hidden. import React from "react"; import { NavLink } ...