using a single controller to manage multiple pages

I created a website with routes using $routeProvider. For each page, I created a controller that looks like this:

   myApp.config(function ($routeProvider) {
     $routeProvider
         
         .when('/category/Web development', {
            templateUrl: 'pages/web-dev.html',
            controller: 'catCtrl'
        })
         .when('/category/Game Programming', {
            templateUrl: 'pages/game-programming.html',
            controller: 'catCtrl2'
        })     

     // Controller for category Web Development    
     myApp.controller('catCtrl', function ($scope, $http) {
        $http.get("http://localhost/biblioteka/public/index/web-dev")
         .then(function (response) {
            $scope.books = response.data;
        });

        $http.get("http://localhost/biblioteka/public/category" )
         .then(function (response) {
             $scope.categories = response.data;
         });
        
         // Other functions specific to this controller
     });
     
     // Controller for category Game Programming
     myApp.controller('catCtrl2', function ($scope, $http) {
        $http.get("http://localhost/biblioteka/public/index/game-programming")
         .then(function (response) {
            $scope.books = response.data;
        });

        $http.get("http://localhost/biblioteka/public/category")
         .then(function (response) {
             $scope.categories = response.data;
         });

         // Other functions specific to this controller
     });

Both controllers have the same content, but I would like to consolidate them into one controller for different pages. Do you have any advice on how I could achieve this? I tried setting the same controller in $routeProvider but it didn't work :(

Answer №1

A suggested approach to tackle this could be as follows:

myApp.config(['$routeProvider', function($routeProvider) {
    $routeProvider.when('/category/:category', {
    templateUrl: function (urlattr) {
        return '/category/' + urlattr.category + '.html';
    },
    controller: 'CategoryController',
    controllerAs: 'categoryCtrl'
  }).otherwise({
    redirectTo: '/category/web_development'
  });
}]);
myApp.controller('CategoryController', ['$routeParams', '$http', function ($routeParams, $http) {
    var categoryCtrl = this;
  // Utilizing $http based on $routeParams.category
}]);

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

Creating a method for a Discord Bot to communicate through a Webhook (loop)

I am looking to enhance my bot's functionality by implementing a webhook triggered by a specific command. Once activated, the webhook should send a message at regular intervals. The idea is to obtain the token and ID of the created webhook, and then ...

Steps for successfully sending data to a MenuItem event handlerExplanation on how to

My issue arises when I attempt to render a Menu for each element in an array, as the click handlers for the items only receive the final element in the array rather than the specific element used for that particular render. The scenario involves having a ...

Raising the css value for each element that is impacted

I am faced with an infinite number of elements that I need to arrange next to each other. Each element has a class called "box". My goal is to separate each box by 10px increments, meaning the first element will have a left property of 0px, the second 10px ...

Access social media login functionality from the client side using AngularJS

I am currently implementing social login in Angular using satellizer. However, I came across a section in the documentation that mentions the need for server-side code as well. The specific lines are provided below: "Additionally, authorization (obtaining ...

Tips for implementing paths instead of GET variables in PHP?

I've encountered an issue where my previous question was closed for the wrong reason. Basically, I have folders that contain a PHP file {dynamic}/blog/index.php. How can I enable someone to access example.com/folders/{dynamic}/blog/unique as if it w ...

Utilizing an Async API call from a separate page and passing it as a component input

I recently set up an asynchronous API fetch in one of my .JS files and then invoked it from another JS file to output the result using console.log. (Is there a more efficient method for achieving this?) Now, my aim is to utilize the fields of the response ...

Is there a simple method to refresh a JSP or Spring MVC page using AJAX?

I'm tackling a seemingly basic question in Java web development here, but I could use some guidance. How can I refresh data on a JSP page? I understand the fundamentals (utilize jQuery for AJAX, Spring MVC for the "Controller" & handle data reque ...

How Keyof can render an object undefined and prevent accurate verification

Encountering TS2532 error: Object is possibly 'undefined' while attempting to access an object's value by dynamically selecting the key. TypeScript seems to be restricting me from checking the field values, and I'm unsure of the underly ...

Guide to extracting a specific value from a JSON object with JavaScript

When working with JavaScript and fetching data from an API, the structure of the data retrieved may look something like this: [{ "word":"gentleman", "score":42722, "tags":["syn","n"] }, { "word":"serviceman", "score":38277, "tags":[ ...

Discover the method for tracking idle time with jQuery and PHP

I have a script that utilizes PHP sessions through a custom class. One of the methods in this class calculates the remaining seconds before the session expires. Whenever the user refreshes the page or opens a new one, the idle time counter is reset using ...

Tips for centering a resized image within a container:

I adjusted the width and height to "max" for my images inside the container, and while wider images fit perfectly, taller ones seem to shift left of the container. I tried researching about adjusting using "max-width" but still facing issues. Here's t ...

Switching images through onmouseover, onmouseout, and onclick interactions

I have two images named img1 and img2. Here is my code: function roll(id, img_name, event_name, img_id) { var state ; if(event_name == 'mouseover') { state = false;rollover();} else if(event_name == 'mouseout') { ...

What are some common applications of the QMap datatype in QML?

Let's say I have a simple QMap declared and initialized with values inside C++ and properly exposed to QML. C++ QMap<QString, QMap<QString, QString>> airflow_buttons_; //simple getter [[nodiscard]] QMap<QString, QMap<QString, QStr ...

Tips on incorporating the wait function within the evaluation_now action in Nightmare?

While I am incorporating Nightmare actions in my script, a question arises regarding the use of the wait function within the evaluate_now function. How can I utilize the wait function within the evaluate_now function? I am aware that I can simply use the ...

Implement CSRF protection for wicket ajax requests by adding the necessary header

I'm currently working on a website created with Apache Wicket and we're looking to enhance its security by implementing CSRF protection. Our goal is to keep it stateless by using a double submit pattern. For forms, we are planning to include a h ...

Leveraging class names to dynamically apply CSS styles to components based on their props value

In the process of developing a collection of reusable components, I have utilized material-ui and styled them with CSS. One specific requirement is to dynamically set the width of a component through a prop passed into a custom button. My goal is to lever ...

What are the mechanics behind the functionality of ES6 class instance variables?

I'm encountering an issue with the following code that is not behaving as expected: import React, { Component } from 'react'; let result = null; class MyData extends Component { _getData = () => { fetch(url) .then(response = ...

Creating a new list by grouping elements from an existing list

I have successfully received data from my API in the following format: [ {grade: "Grade A", id: 1, ifsGrade: "A1XX", ifsType: "01XX", points: 22, type: "Type_1"}, {grade: "Grade B", id: 2, ifsGrade: &quo ...

Obtain all subelements from the entity

In my Vue project, I am attempting to collect and POST some values to the server. However, I am finding the current implementation to be somewhat frustrating. Within a Vue method, I have a function that POSTs the collected values from the original object: ...

Are there any concerns about memory leaks when using recursive JavaScript Objects?

Our model entities are passed through the API in JSON format, allowing us to inflate them client-side for use on both the server and client sides. These entities have standard Hibernate bi-directional relationships. As you navigate through an object in the ...