Using AngularJS to Nest ng-view within ng-repeat

I have a collection of items. Each item has buttons to display its details and comments within this ng-view section.

It is necessary for the user to view all available product details on one page, for example.

Below is the HTML list:

<div ng-controller="ProductsApp">
    <ul>
      <li ng-repeat="product in products">
        <p>{{product.Name}}</p>
        <p>
            <a href="#/details/{{product.Id}}">Details</a>
            <a href="#/comments/{{product.Id}}">Comments</a>
        </p>
        <div ng-view="productView{{product.Id}}">
        </div>
      </li>
    </ul>
</div>

Next is my routing setup:

angular
    .module('ProductsApp',[])
    .config(function ($routeProvider) {
        $routeProvider.
            when('/details/:productId', {
                controller : DetailsCtrl, 
                templateUrl : 'Details.html',
                view: 'productView:productId'
            }).            
            when('/comments/:productId', {
                controller : CommentsCtrl, 
                templateUrl : 'Comments.html',
                view: 'productView:productId'
            }).

This is my controller function:

function DetailsCtrl ($scope, $window, $http, DetailsList) {    
    var productId = $routeParams.productId;
    $scope.Details[productId] = DetailsList.get({'productId' : productId});
}

Finally, the Details.html looks like this:

<div>
    Name: {{Details[productId].Name}}
    Size: {{Details[productId].Size}}
    ...
</div>

I have two questions regarding this implementation:

  1. Is this the correct approach? Are there alternative methods?
  2. How can I retrieve the productId for the current ng-view? Name: {{Details[productId].Name}}

Thank you!!!

Answer №1

There might be a way to achieve your goal with your current approach, but it seems like a more complex solution than necessary. Angular typically works best when handling one route per controller at a time, and trying to work around this could involve some hacky tactics.

Instead, take a look at the tabs example on the main page of http://angularjs.org/. Personally, I would suggest using a directive for this task, although it's possible to manage without one. Here's a rough implementation:

<span ng-click='showDetails[$index] = true'>Details</span>
<span ng-click='showDetails[$index] = false'>Comments</span>

<div ng-show='showDetails[$index]'>Details here.</div>
<div ng-show='!showDetails[$index]'>Comments here.</div>

If you require specific behavior for Details and Comments that necessitate controllers, then directives may be the way to go. Create a directive for each (each with its own controller) so that the code simplifies to something like this:

<span ng-click='showDetails[$index] = true'>Details</span>
<span ng-click='showDetails[$index] = false'>Comments</span>

<details ng-show='showDetails[$index]'> data-id='{{product.id}}'></details>
<comments ng-show='!showDetails[$index]'> data-id='{{product.id}}'></comments>

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 ensure the options/choices div reaches its ideal width?

Check out my StackBlitz project that I've set up In the styles.css file, you'll notice that I defined a fixed width of 650px for the option dropdown div, which is currently working fine @import '~bootstrap/dist/css/bootstrap.min.css'; ...

What are the appropriate situations to utilize Q.defer versus using Promise.resolve/reject?

I've been working with nodejs and I'm curious about when to use Q defer over Promise.resolve/reject? There are numerous examples of both methods, such as: // using Q defer function oneWay(myVal) { var deferred = Q.defer(); if (myVal < 0) ...

The element 'flat' is not found within the specified type

My challenge involves utilizing the flat() method in a TypeScript script. In my tsconfig.json file, I have set the target to es2017 and defined an interface for the input variable. However, I keep encountering this error message: Property 'flat' ...

Set the background-color of each <td> element to be equal to a value in the array, with each group of three elements having the same

I am trying to color every <td> element in a row of three columns with the same color using the following code: for (var i = 0; itr < $("td").length; i++) { $("td").eq(i).css("background-color", Colors[i]); } However, this code colors each i ...

Is the latest update of Gatsby incompatible with Material UI?

Encountering an issue while running this command portfolio % npm install gatsby-theme-material-ui npm ERR! code ERESOLVE npm ERR! ERESOLVE unable to resolve dependency tree npm ERR! npm ERR! While resolving: <a href="/cdn-cgi/l/email-protection" class= ...

Despite declaring a default export, the code does not include one

Software decays over time. After making a small modification to a GitHub project that was three years old, the rebuild failed due to automatic security patches. I managed to fix everything except for an issue with a default import. The specific error mess ...

What is the correct way to transform an Error object to a string in Node.js?

Every time I input a duplicate entry in mysql, this error pops up. { [Error: ER_DUP_ENTRY: Duplicate entry '<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="35465458455950755258545c591b-565a58">[email protected]< ...

Show items according to the side menu in Onsen-UI

After successfully populating the sidemenu with OpenCart categories and displaying products on the main page, I am facing an issue when it comes to showing specific products under a particular category. For example, clicking on 'PC' in the side ...

Angular routes cause a glitch in the Bootstrap navbar, causing it to shift to the left on certain active

Apologies for the simple question, I am new to web design and couldn't find a solution even after extensive googling and searching. The issue I am facing is that when clicking on "EX5" or "EX6" in my navbar, it shifts to the left side of the screen i ...

Experiencing a problem with obtaining the .offset().top value of an element within an iframe resulting in an

Encountering an issue with Firefox and Safari where attempting to retrieve the .offset().top value from an element within an iframe results in undefined when trying to access this value. This functionality seems to be working properly in Chrome, Edge, and ...

I have noticed that there are 3 images following the same logical sequence, however only the first 2 images seem to be functioning correctly. Can you help

Update: I have found a solution that works. You can check it out here: https://codepen.io/kristianBan/pen/RwNdRMO I have a scenario with 3 images where clicking on one should give it a red outline while removing any outline from the other two. The first t ...

Troubleshooting problem with fetching data from Angular API

Looking to use Angular to extract a specific value from the following API: Current code snippet being utilized: app.controller("api", function($scope, $http) { $scope.home = "This is the homepage"; $scope.getRequest = function() { console. ...

Detecting When an Input has an :invalid Selector in Jquery

Here is the code snippet I am currently working with: HTML <input type="text" data-value="1" data-type="input-records" placeholder="Value" pattern="\d{1,4}$" /> CSS input[type=text]:invalid { background-color: red; } Javascript $("[data-ty ...

React-query: When looping through useMutation, only the data from the last request can be accessed

Iterating over an array and applying a mutation to each element array?.forEach((item, index) => { mutate( { ...item }, { onSuccess: ({ id }) => { console.log(id) }, } ); }); The n ...

Error: Unable to modify a property that is marked as read-only on object '#<Object>' in Redux Toolkit slice for Firebase Storage in React Native

Hey there! I've been working on setting my downloadUrl after uploading to firebase storage using Redux Toolkit, but I'm facing some challenges. While I have a workaround, I'd prefer to do it the right way. Unfortunately, I can't seem to ...

Angular encountered a 403 error while making an HTTP POST request

After successfully implementing angularJS validation in my form on localhost, I encountered a 403 Error (Forbidden) on line 72 of my angular.min.js file when trying to upload the code to my web server. I have tried numerous solutions but remain stuck on t ...

Eliminate the need for require statements in TypeScript-generated JavaScript files

I am working on a website project and utilizing TypeScript for development. While using the tsc compiler, I noticed that all my JavaScript code compiles correctly. However, when I include an import statement in my TypeScript files, it gets compiled into J ...

linking to a page that shows the user's chosen option from a dropdown menu

One of the challenges I encountered was creating a feature that allows users to share a specific selection from multiple dropdown lists on a page. Essentially, my goal was to enable users to send a link that would direct others to the same page with the ex ...

Retrieve the origin of the copied text

While working on a Vue application, I'm curious to know if it's possible to access the source of pasted text. For example, whether the pasted text originated from your own application, Word, or Notepad? I attempted the code below but was unable ...

Using MomentJS along with Timezones to accurately display Datetime while accounting for offsets

I am utilizing moment.js along with timezones to generate a datetime linked to a specific timezone: var datetime = moment.tz("2016-08-16 21:51:28","Europe/London"); Due to the recognition of DST (daylight saving time) by this constructor, moment.js will ...