Transferring Data from Controller to HTML in AngularJS Version 1

Recently, I started working with angularjs on a new project that involves three main HTML files. The first file is index.html, which contains the ng-view directive. The second file is home.html, where various products are displayed from a database. Each product listed on home.html functions as a link to another page called product.html, which provides detailed information about a single product.

However, I encountered an issue where clicking on a product in home.html for the first time would display a blank product.html page. Subsequent clicks on different products in home.html only showed data from the previous click. This pattern continued with each new click, displaying data from the previous selection rather than the current one.

The structure of home.html is as follows:

<div ng-controller="productController" class="homeMainDiv">

    <!-- Product DIV Start -->
    <div data-ng-init="onloadFun()">
        <div>
        <table style="width:100%">
            <tr ng-repeat="product in products" ng-switch on="$index % 3">
              <td ng-switch-when="0">

                <a target="_blank" href={{products[$index].product_Url}}>
                        <img src="{{products[$index].product_Url}}" style="width:150px">
                </a>
                <a href="#product" style="cursor: pointer; margin-top: 5px;" ng-click="getProductById(products[$index].product_Url)">View Product Details and Buy Options</a>
              </td>
              <td ng-switch-when="0">
                <span ng-show="products[$index+1]">

                  <a target="_blank" href={{products[$index+1].product_Url}}>
                        <img src="{{products[$index+1].product_Url}}" style="width:150px">
                 </a>
                 <a href="#product" style="cursor: pointer; margin-top: 5px;" ng-click="getProductById(products[$index+1].product_Url)">View Product Details and Buy Options</a>

                </span>
              </td>
              <td ng-switch-when="0">
                <span ng-show="products[$index+2]">    
                  <a target="_blank" href={{products[$index+2].product_Url}}>
                        <img src="{{products[$index+2].product_Url}}" style="width:150px">
                  </a>
                  <a href="#product" style="cursor: pointer; margin-top: 5px;" ng-click="getProductById(products[$index+2].product_Url)">View Product Details and Buy Options</a>

                </span>
              </td>
            </tr>
        </table>
    </div>
</div></div>

The product.html page looks like this:

<div ng-controller="productController">
    <div style="margin-top: 307px;">
        <h1>Hello Product</h1>
        <img src="{{productById.product_Url}}" style="width:150px">
        <br>
        <a href="#">View Product Details and Buy Options</a>
    </div>
</div>

Finally, here's a snippet from script.js:

var gelovenIndia = angular.module('apparel', ['ngRoute']);

    gelovenIndia.config(function ($routeProvider,$locationProvider) {
        console.log("In config");
        $locationProvider.hashPrefix('');
        $routeProvider

     // route for the home page
        .when('/', {
            templateUrl : 'pages/home.html',
            controller  : 'productController'
        })

        // route for the your story page
        .when('/product', {
            templateUrl : 'pages/product.html',
            controller  : 'productController'
        });

    });

    gelovenIndia.controller('productController', function($scope, $http, $location, productService) {
         console.log("In productController");
         $scope.product = {};

         // More code included...

        });


    gelovenIndia.service('productService', function() {
        console.log("2");
          var product;

          // More code included...

        });

If anyone has insights or solutions regarding this issue, please share them. Thank you.

Answer №1

You don't need to utilize both the ng-click and href attributes for redirecting to a new page. It is recommended to stick with one method. I would advise removing the href attribute and redirecting using a function call and the $location service.

<a style="cursor: pointer; margin-top: 5px;" ng-click="getProductById(products[$index].product_Url)">View Product Details and Buy Options</a>

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 setting up routing based on the current value of the $rootScope variable

I am in need of creating a data collection application that functions like a "wizard" using AngularJS. As the user moves through each step of the wizard, I am presented with a decision to make: a) include a separate "Next" button on each page section tha ...

Experimenting with mocha and Nightmare.js, utilizing traditional syntax and without the use of ES6 features

Here is a real-world example that I am using: How to Use Nightmare.js without ES6 Syntax and Yield However, when I include it in a Mocha test, it times out. Here's the code snippet: describe('Google', function() { it('should perform ...

Is it possible to generate a component dynamically using a string template?

I have a Component called "CDataTable" that renders columns in a for loop. Inside the loop, there is a template: <template v-if="typeof col.template !== 'undefined'" #body="{data}"> <component :is="compile(co ...

Utilizing One-to-Many Microphone Streaming Technology

I'm looking to create a unique one-to-many microphone streaming system where a user can record from their microphone and others can listen in. I also need to be able to record the microphone session. Would it be better to use WebRTC for client commun ...

What is the best way to assign the value of an HTTP GET request to a subarray in Angular 8

Attempting to store data in a sub-array (nested array) but despite receiving good response data, the values are not being pushed into the subarray. Instead, an empty array is returned. for (var j=0;j<this.imagesdataarray.length;j++){ this.http.g ...

Obtain the text value from an HTML button in JSP code

Here is an HTML tag that I have: <button type="submit" name=<%=s %> value=<%=s %>><%=s%></button> The <%=s %> represents a String with white spaces stored on the server, such as "file one". I am facing an issue with extr ...

What is the best way to retrieve and save the titles of checked boxes in the Autocomplete using state with hooks?

I've implemented the React Material-UI Autocomplete feature with checkboxes in my project. Here is what I have so far in my code (check out demo.js for details): https://codesandbox.io/s/material-demo-rxbhz?fontsize=14&hidenavigation=1&theme=d ...

Prevent clicking on the <div> element for a duration of 200 milliseconds

I need to make this box move up and down, but prevent users from clicking it rapidly multiple times to watch it go up and down too quickly. How can I add a 200 millisecond delay on the click or disable clicking for that duration? View the jsfiddle example ...

Can you rely on a specific order when gathering reactions in a discord.js bot?

Imagine a scenario where a bot is collecting reactions to represent event registrations. To prevent any potential race conditions, I have secured the underlying data structure with a mutex. However, the issue of priority still remains unresolved as user # ...

Is there a way to preserve EXIF data when converting an image to base64?

I am currently facing an issue with reading a local image that has been created with a different exif.Orientation based on the degree of rotation. const exifData = piexif.load(data.toString("binary")); // Assign the desired orientation value ...

A guide to extracting text from HTML elements with puppeteer

This particular query has most likely been asked numerous times, but despite my extensive search, none of the solutions have proven effective in my case. Here is the Div snippet I am currently dealing with: <div class="dataTables_info" id=&qu ...

Node.js has no trouble loading HTML files, however, it seems to encounter issues when trying to

Having a bit of trouble with my JavaScript skills as I try to load my index.html file (seems like it should be the 5th easiest thing to do in JavaScript). Let me get straight to the point; when I manually open my index.html, it loads perfectly WITH the CS ...

How can I implement Jquery validation engine ajax for two different fields using the same function?

The jQuery validation engine plugin has a unique feature of performing ajax validation. However, there is a minor inconvenience with this functionality. Instead of validating the field name, it sends the field ID for validation. Why does this pose a prob ...

Parsing JSON data in Java through static error monitoring

I'm looking to utilize Java to load a JSON file and save the data into variables Despite my attempts, I keep encountering an error import com.google.gson.JsonElement; import com.google.gson.JsonObject; import com.google.gson.JsonParser; import java. ...

Is there a way to modify the log() function to handle multiple arguments?

Recently, I've been utilizing this logger in node.js: // Found on stackoverflow: https://stackoverflow.com/questions/9781218/how-to-change-node-jss-console-font-color function logC(text) { console.log('\x1b[36m%s\x1b[0m', text); ...

Proceed with downloading the file only when a checkbox has been ticked off and the form has been

Is there a way to make a PDF download only when a user checks a checkbox and submits the form, rather than just checking the checkbox and hitting submit? I am limited to using Jquery or plain javascript and do not have access to backend files. The checkbox ...

What is the process for bundling a separate JavaScript file with Webpack5?

I am new to the world of webpack. I have 2 javascript files and I want to designate one as the main entry file. However, for the other file, I only want to include it in specific files. For example, looking at the file structure below, main.js is my entr ...

AngularJS and Ionic Framework - Click on a specific row to interact with it

I am struggling to open a new page when an item is touched in my HTML code. Despite trying multiple times, I can't seem to make it work and I'm at a loss as to why. Below is the snippet of my HTML: <!DOCTYPE html> <html> <hea ...

Creating a Vue.js component that animates text to fade in and out within a textarea when a button

I need assistance with updating a <textarea> element in my Vue application. Currently, I have the textarea bound to some data in my state. However, when a button is clicked, I want the existing data in the textarea to fade out and be replaced with ne ...

Sorting through a JavaScript array

I am facing a peculiar problem while trying to filter an array in TypeScript. Here is the structure of my object: Sigma.model.ts export class Sigma { sigmaId: number; name: string; userId: number; starId: string; } `` The starId property contains com ...