Is it possible to use AngularJS with a single template that caters to all categories

Apologies for any language barriers, I have been following the guidance provided in the phoneCat app example. Specifically, I am working on integrating one category (phone list and detail partial templates) into my project. For instance, I aim to include multiple categories like cars, phones, and fashion, all within a single category.html file accessed via URLs such as localhost/myApp/#/car or localhost/myApp/#/phone.

Main Layout:

<div ng-view></div>

JS File:

.config(['$routeProvider',
function($routeProvider) {
  $routeProvider
    // route for fashion
    .when('/fashion', {
      templateUrl: 'partials/category.html',
      controller: 'fashionCtrl'
     })
    // route for car
    .when('/car', {
      templateUrl: 'partials/category.html',
      controller: 'carCtrl'
    })
.. including controllers for fashionCtrl and carCtrl

Partial Template HTML (category.html):

template for car
...................
template for fashion
...................
template for phone

When accessing the path /#/fashion, it currently displays both categories, but ideally, I want only one - either fashion or car. Can anyone provide a solution to this issue? Thank you for your assistance!

Answer №1

It appears that what you are trying to achieve is sharing both the controller and template, which is a common scenario...

Instead of setting up multiple routes, you can simply have a single route:

.config(['$routeProvider',
function($routeProvider) {
  $routeProvider
    // route for electronics
    .when('/:category', {
      templateUrl: 'partials/category.html',
      controller: 'categoryController'
     })

In your controller, use $routeParams to retrieve the currently selected category and populate your template with the shared data.

.controller('categoryController', ['$scope', '$routeProvider', function($scope, $routeParams) {
    $scope.category = $routeParams.category;
    $scope.items = fetchDataFromService($routeParams.category);
}])

Example: http://plnkr.co/edit/dtrZMAcbsbzpWsd9e7Uy?p=preview

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

Tips for establishing a shared child state within an AngularJS application

Is it possible to activate an authenticating modal when the token expires on the client side? I would like for this to be a universal child state that can be accessed from any state. Can this be achieved? ...

Angular routes can cause object attributes to become undefined

I am new to Angular and struggling with an issue. Despite reading numerous similar questions and answers related to AJAX, async programming, my problem remains unsolved. When I click on the 'Details' button to view product details, the routing wo ...

Browse through different states by clicking on the <a> </a> tag

Is there a way to switch between states defined by $stateProvider when clicking on the <a> </a> tag? Below are the states I have set up: $stateProvider //region page States .state('page1', { url: "/pg1", ...

Issue with AngularJS filter not functioning properly

I have a specific situation where I am using an ng-repeat directive in the following manner: {"ng-repeat" => "city in cities() | filter: search"} In this context, each city object is structured like so: { attributes: {name: 'Boston'} } Furt ...

What is the process for integrating personalized routes in angular.js?

Currently, I have set up a route as follows: .state('home.blog', { url: "/blog", templateUrl: "blog.html", controller: "BlogController" }) The current route is localhost:3000/home/blog, but I want to change it to localhost:3000/blog. Desp ...

I'm looking to use $resource to generate a unique query that can pass arguments to the find method in mongoose through req.body. How can I accomplish

I would like to implement a custom query method in this manner: $scope.modules = dataFac.getModules().customQuery({name: /test/}) .$promise.then(function(response){ $scope.modules = response; ...

AngularJs is being used to extract data from Firebase with the help of $value, $id, and

I have been working on retrieving data from Firebase in my HTML using AngularJS. Everything is functioning well, however, when I access the child node, the data is displayed in an unexpected format. Please refer to the images below for more details: This ...

Encountering a Post Error when Using MongoDB with Node.js

I encountered an issue when attempting to post to the DB, receiving an Error: 'Cannot POST /api/postCampaign' and a 404 (Not Found) error for . My goal is to store data in a MongoDB database. Initially, this code was functioning properly as it co ...

pass boolean value from middleware to express route handler

In a middleware I have defined, my aim is to fetch and return a boolean value like this: module.exports = { authenticatepracticename: function(pname) { ecollection.find({ $and: [{'name':pname},{'status' : 'active&apos ...

Implement the AngularJS orderby filter based on a checkbox selection

Is it possible to use the angularJS orderby filter with a checkbox for ordering columns? I currently have this working as expected: <tr ng-repeat="player in players | orderBy:'id':true | rangeFilter:min:max"> <td>{{player.id}}</ ...

Is there a way to pass asynchronous data to a UI Bootstrap modal in Angular using resolve?

I'm having trouble injecting async data into a UI Bootstrap modal in Angular. The code below shows the controller responsible for opening the modal. import insertOpportunityModal from './insertOpportunityModal.html'; export default class O ...

Having trouble inserting a new row into the AngularJS table?

Having trouble adding a new row to the table in angularjs when clicking the add button. Here is the link to the Plunkr example -https://plnkr.co/edit/s7XAaG4JbvbTTxiZ0V2z?p=preview The HTML code snippet is as follows: <html> <head> <script ...

I am interested in determining the sum of ng-repeat results

I need help with calculating the total amount of ng-repeat items based on a condition. Here is an example of my table structure: <tr ng-repeat="Company in Companies track by $index"> <td>Department</td> <td>Amount</td> & ...

Modify the length of an array using a number input field

Currently, I am working with an array that contains objects and I want to dynamically change the number of objects in this array based on user input from a number type input box. Whenever the number in the input box is increased, I need to increase the len ...

Detecting when a directive element has not been clicked in Angular may involve checking for certain event behaviors

I am looking to enhance the functionality of the "deselect" feature in multiple directives like buttons and popovers. Specifically, I want my functions to activate when the user clicks on an element that is not part of the directive template. Currently, I ...

Tips for successfully implementing Angular.js validation within the confines of a <form> element

Having trouble getting my code to work when I place my app inside the <form name="myForm"> tag. Any suggestions on how to make it function properly? (It works when I place myForm inside ng-app, but my app needs to be within the <form> tag) < ...

Clicking on ng does not trigger the function on its own

Seeking assistance in refreshing a captcha code by clicking on a button. However, the function itself is not being triggered. Is there something missing? Here is the snippet of my controller.js code: $scope.goCaptcha = function() { console.log('enter ...

The functionality of Ng-Show is acting up

$scope.stay = function() { alert("Inside Keep me In") $scope.timed = false; $scope.isLogStatus = true; } $scope.displayAlert = function() { $scope.timed = true; alert("inside display") } function idleTimer() { var t; $window.o ...

Issue with AngularJS: $http header 'Content-Type' not being appended to the header

When making a GET request using $http, I encountered an issue where I needed to append 'Content-Type': 'application/json' in the header to avoid getting a 415 (Unsupported Media Type) error. I am running Apache 2.2.13 with ProxyPass an ...

Encountering issues with gulp-angular-templatecache while processing angular templates through pipelining

I've encountered an issue with gulp-angular-templatecache in my gulpfile. Here's the task causing trouble: gulp.task('templates', function() { return gulp.src(paths.angularTemplates) .pipe(templateCache()) ...