Dynamic content loading in Angular through HTML upon clicking

In the process of developing an Angular store, I aim to create anchor tags for each product so that clicking on a tag will display the selected product information in an HTML template below.

Below is the current code snippet:

(function() {
var app = angular.module('store', [ ]);

app.controller('StoreController', function() {
this.products = products;
});

var products= [
{
 category: "Category 1",
 products:  [{
  name: "Product 1",
  description: "Lorem ipsum dalor sit amet"
   },{ 
    name: "Product 2",
    description: "Lorem ipsum dalor sit amet"
   }],
 },{
 category: "Category 2",
 products:  [{
  name: "Product 3",
  description: "Lorem ipsum dalor sit amet"
   },{ 
    name: "Product 4",
    description: "Lorem ipsum dalor sit amet"
   }],
 }];
})();
#results {
  margin-top:1em;
}
<!DOCTYPE html>
<html ng-app="store">

  <head>
    <link rel="stylesheet" href="style.css">
  </head>

  <body ng-controller="StoreController as store">
    
  <section>
  <div ng-repeat="product in store.products" class="product">
  <h2>{{product.category}}</h2>
  <div ng-repeat="product in product.products">
      <a href ng-click="select(product)">{{product.name}}</a>
      </div>
  </div>
  </section>
  
  <section id="results">
    Selected product data should be loaded here:
  <div class="product">
        <h2>{{selected.name}}</h2>
        <div class="product-desc"><p>{{selected.description}}</p></div>
     </div>
    </section>
  
  <script type="text/javascript" src="https://cdnjs.cloudflare.com/ajax/libs/angular.js/1.6.3/angular.min.js"></script>
  </body>

</html>

I reckon that incorporating a JavaScript function into the app controller to handle the selected product is necessary, but I am unsure about how to proceed with it.

Answer №1

It is recommended to use the following code snippet:

 <a href ng-click="store.select(product)">{{product.name}}</a>

In the Controller section, you can implement the functionality as shown below:

var vm = this;
this.products = products;

vm.select = function(product){
    vm.selected = product;
}

DEMO

(function () {
        var app = angular.module('store', []);

        app.controller('StoreController', function () {
                var vm = this;
                this.products = products;

                vm.select = function (product) {
                        vm.selected = product;
                }
        });
        var products = [{
                category: "Category 1",
                products: [{
                        name: "Product 1",
                        description: "Lorem ipsum dalor sit amet"
                }, {
                        name: "Product 2",
                        description: "Lorem ipsum dalor sit amet"
                }],
        }, {
                category: "Category 2",
                products: [{
                        name: "Product 3",
                        description: "Lorem ipsum dalor sit amet"
                }, {
                        name: "Product 4",
                        description: "Lorem ipsum dalor sit amet"
                }],
        }];
})();
#results {
  margin-top:1em;
}
<!DOCTYPE html>
<html ng-app="store">
<head>
    <link rel="stylesheet" href="style.css">
</head>
<body ng-controller="StoreController as vm">
    <section>
        <div ng-repeat="product in vm.products" class="product">
            <h2>{{product.category}}</h2>
            <div ng-repeat="product in product.products">
                <a href ng-click="vm.select(product)">{{product.name}}</a>
            </div>
        </div>
    </section>
    <section id="results">
        Selected product data should be loaded here:
        <div class="product">
            <h2>{{vm.selected.name}}</h2>
            <div class="product-desc">
                <p>{{vm.selected.description}}</p>
            </div>
        </div>
    </section>
    <script type="text/javascript" src="https://cdnjs.cloudflare.com/ajax/libs/angular.js/1.6.3/angular.min.js"></script>
</body>

</html>

Answer №2

To implement a new feature in your controller, follow these steps:

app.controller('ShopController', function() {
    var ctrl = this;
    this.items = items;

    ctrl.selectItem = function(item){
        ctrl.selectedItem = item;
    }
});

In your HTML code, make sure to prefix all controller-related elements with 'shop'. Take a look at the example snippet below:

(function() {
var app = angular.module('shop', [ ]);

app.controller('ShopController', function() {
var ctrl = this;
this.items = items;

    ctrl.selectItem = function(item){
        ctrl.selectedItem = item;
    }
});

var items= [
{
 category: "Category 1",
 items:  [{
  name: "Item 1",
  description: "Lorem ipsum dalor sit amet"
   },{ 
    name: "Item 2",
    description: "Lorem ipsum dalor sit amet"
   }],
 },{
 category: "Category 2",
 items:  [{
  name: "Item 3",
  description: "Lorem ipsum dalor sit amet"
   },{ 
    name: "Item 4",
    description: "Lorem ipsum dalor sit amet"
   }],
 }];
})();
#results {
  margin-top:1em;
}
<!DOCTYPE html>
<html ng-app="shop">

  <head>
    <link rel="stylesheet" href="style.css">
  </head>

  <body ng-controller="ShopController as shop">
  
  <section>
  <div ng-repeat="item in shop.items" class="item">
  <h2>{{item.category}}</h2>
  <div ng-repeat="item in item.items">
      <a href ng-click="shop.selectItem(item)">{{item.name}}</a>
      </div>
  </div>
  </section>
  
  <section id="results">
    Selected item details will be displayed here:
  <div class="item">
        <h2>{{shop.selectedItem.name}}</h2>
        <div class="item-desc"><p>{{shop.selectedItem.description}}</p></div>
     </div>
    </section>
  
  <script type="text/javascript" src="https://cdnjs.cloudflare.com/ajax/libs/angular.js/1.6.3/angular.min.js"></script>
  </body>

</html>

Answer №3

Simply include a JavaScript function. Your assumption is spot on.

$scope.onSelect = function(item) {
   $scope.selectedItem = item;
};

When working in HTML, make sure to rename the function as onSelect(item) rather than select(item).

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

Utilizing the this.setState function within a callback

In my current project, I've encountered an issue with setting the state in a Twitter timeline react component. The code snippet causing trouble is as follows: componentWillMount: function() { twitter.get('statuses/user_timeline', ...

Issue with Axios code execution following `.then` statement

Recently diving into the world of react/nodejs/express/javascript, I encountered an interesting challenge: My goal is to retrieve a number, increment it by 1, use this new number (newFreshId) to create a new javascript object, and finally add this event t ...

When THREE.js repeatedly loads and plays the same animated GLB file in a loop, only the final model that is loaded will

I'm attempting to create a loop of animated butterflies, but I'm encountering an issue where only the first or last butterfly actually animates. I suspect this is due to the need to clone the gltf.scene, but there's a known bug with cloning ...

Python3 was installed, but the version couldn't be located

After trying to install a module on NPM, I encountered this error despite already having Python 3 installed and my ENV path set correctly. I attempted to install the NPM module, but it did not work as expected. ...

The SvelteKit server successfully loaded data, displaying it on the sources/index page in the Chrome

I am currently in the process of developing a basic web application that utilizes self-hosted Pocketbase on the backend and SvelteKit as a meta framework. Recently, I discovered that the data loaded by my server is visible in the browser's sources/in ...

How can Protractor be used to test content before Angular is fully loaded?

In my opinion, it's crucial to notify users when an Angular-based application is loading. For instance, in the case of Angular 2, you could use something like <view>Loading...</view>. I'm confident that there must be a similar method ...

Creating a real-time clock in a single line console log format using NodeJS

To create a live clock in a single line display within a browser, we can utilize setInterval and manipulate the content inside an HTML element like so: var span = document.getElementById('span'); function time() { var d = new Date ...

What is causing my basic angularjs to not function properly?

In my angularjs test instance, I am using a global variable but the alert tag is not functioning as expected. This code snippet is from my first example on codeschool. Any thoughts on why the alert is not running? <!DOCTYPE html> <html xmlns="ht ...

What is the best way to use Immer to update Zustand state when incorporating objects that are added through a controlled form using React-Hook-

Having some trouble with integrating Zustand and Immer using React-Hook-Form. My goal is to capture a series of values from a form, store them in a list, and allow for the addition of new objects to that list. In this scenario, the user inputs data for a ...

Is it possible to use JavaScript to upload and manipulate multiple HTML files, replacing text within them to create new output HTML pages?

Is it possible to modify the following code to accept multiple files, process them, and then return the output? <html> <head> </head> <body> <div> <label for="text">Choose file</label> <inp ...

"Troubleshooting: The unique key prop is not functioning as expected with a

I am continuously receiving the warning message: Each child in a list should have a unique "key" prop. Even though I have assigned a key with an index number to my element, it does not appear in the HTML when inspecting via dev tools. The key values are a ...

Retrieve the ETag header from a PUT request in AngularJS using $http

Need help getting the ETag header from an AngularJS $http.put request using an S3 MultipartUpload. Struggling to read the value, any assistance is welcome. Thank you! $http({ method: 'PUT', url: url, headers: { 'Content-T ...

Leveraging strings as URLs to embed PDFs in Wordpress using PDF Embedder

I'm encountering an issue related to a Wordpress plugin called PDF Embedder, as well as concatenating/using a string with document.write. My goal is to make this code work: <script src="http://nooze.org/wp-content/uploads/scripts/dateGetter.js"> ...

Optimal approach for creating and deploying Docker images

After successfully setting up the initial pipeline for my Angular application, which operates within a Node image in Docker, I followed this process: first, push to Gitlab then initiate a Hook to trigger the Jenkins Build. This is followed by executing a D ...

Utilizing ng-repeat to iterate over a nested array

I need help figuring out how to properly loop through a JSON array and its ingredients/directions array using ng-repeat. The current method I have attempted is not working as expected. Any suggestions or advice would be greatly appreciated! Thank you. Con ...

The module 'angular' appears to be missing within the Angular 2 project

Currently, I am utilizing angular-cli and typescript in an attempt to downgrade an angular2 component for it to function within an angular 1.5 project. However, the module is not being recognized. What could be causing this issue? // Angular 1 Vendo ...

The following middleware is not functioning properly on a local SSL server

When I run my Nextjs app without SSL using "next dev", the middleware functions as expected without any errors. However, if I attempt to run the app with SSL enabled, an empty middleware function triggers an error. The code for the middleware function (l ...

Is there a problem connecting to the MongoDB server?

I am having trouble connecting to the MongoDB server using the link provided below. I have double-checked the password and dbName, but it still won't connect. Can someone please assist me with this? const mongoose = require('mongoose'); ...

Verify the MAC address as the user types

I need to verify a form field for MAC Addresses and have implemented the following code that does the job. $('body').on('keyup', '#macAddess', function(e){ var e = $(this).val(); var r = /([a-f0-9]{2})([a-f0-9]{2})/i, ...

What is the method for a Greasemonkey script to divide a link into three interconnected links?

My goal is to use Greasemonkey to link Redmine issue numbers found in cgit commit messages to their respective issues or projects. The cgit commit message HTML source looks like this: <a href='/editingmodule/commit/?id=49e4a33e0f8b306ded5'&g ...