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

Having trouble setting up discord.js on my device, getting an error message that says "Unable to install discord.js /

Trying to install Discord.JS by using the command npm install discord.js seems to be successful at first, but unfortunately it doesn't work as expected. Upon running the index.js file, an error message pops up indicating that the module discord.js is ...

Utilizing HTML5 Drag and Drop feature to track the initial position of the element being dragged

Currently, I am utilizing the HTML 5 Drag and Drop API to create a sortable list with auto scroll functionality. One crucial aspect I am trying to incorporate is the ability to detect which specific part of an element was grabbed by the user. Take a look ...

Unable to access files using FileOpener2 on Android without receiving an error

My goal is to use FileOpener2 (via ng-cordova) to open a PDF file by implementing the code below: $cordovaFile.checkFile(cordova.file.dataDirectory, attachmentPath) .then((fileEntry) => { // success fileEntry.getMetadata((metadata) ...

Vue.js data does not exhibit reactivity

I am encountering an issue with a non-reactive data object nested inside another object in my Vue.js template. Here is the code snippet: <template> <div> <b-container class="bg-white text-center scrollBehavior" > ...

Filtering a table using jQuery based on the class or data attributes

Issue arises when selecting the first "Icon" shows "Not found", then opting for "Talisman" does not display. It should show "Not Found". Is this achievable? Add the classes f-Icon, f-Ring, f-Neck. Then search for the value by class. Select either "Icon R ...

Ways to eliminate the Vuetify append-icon from the sequential keyboard navigation

In my Vue.js application using Vuetify, I have implemented a series of password fields using v-text-field with an append-icon to toggle text visibility. Here is the code snippet: <v-text-field v-model="password" :append-icon="show1 ? 'mdi-eye& ...

Creating a cinematic demise for a player through the lens of a camera

I've encountered a challenge with destroying the player through the camera in my application. The camera is set to follow the player (the ball), but it can only track the ball moving upwards. My goal is to have the player (ball) destroyed when it reac ...

Ways to recycle the output of the three.js fragment shader

Recently delving into GLSL shaders in three.js, I am currently experimenting with creating a simple and efficient blur effect on a mesh texture. Below is the fragment shader code I have been working on: void blurh(in vec4 inh, out vec4 outh, int r) { ...

Retrieving the selected date from mat-datepicker into a FormControl

When creating a POST request to an API, I encountered an issue with the mat-datepicker field as it throws an error when inside the ngOnInit() call (since nothing is selected yet). Other fields like name, email, etc. work fine, but extracting a value from t ...

Encountering an unfamiliar statement

I'm trying to present my WordPress blog posts in a list using jQuery mobile and JSON API, but when I run the program I encounter the following error: Error: Syntax error, unrecognized expression: div class="entry">undefined ...){var t=e.nodeNa ...

Rails gives a response of HTML when angular sends a resource.get request

Having trouble with Rails 4 responding to an angular resource.get request with HTML instead of JSON. The code snippet for the javascript is as follows: $resource("/questions/:id", {id: "@id"}}.get({id: 16}); The server error occurs because it cannot loc ...

Binding an event to an Angular 2 component directly within its selector code

Looking at my Angular 2 component: import { Component, ElementRef, Renderer } from '@angular/core';; @Component({ selector: 'my-button', templateUrl: 'button.html' }) export class ButtonComponent { private text: string ...

Error: Unable to access 'createInvite' property from undefined variable

Having trouble generating an invite to one of my guild's channels. Here is the code snippet I am using: const { Client } = require("discord.js"); const client = new Client({ intents: [] }); client.on("ready", async () => { ...

I am encountering an issue with my ui-router resolve where it is not returning any information despite no

I am struggling to connect my MongoDb and API REST with my Angular application. It seems like there is an issue with resolution. Currently, I am following a MEAN application tutorial on this website. This snippet shows my ui-router configuration. var ap ...

Tips for incorporating a page route with an HTML extension in Next.js

I'm facing a challenge in converting a non-Next.js page to Next.js while maintaining my SEO ranking. To preserve the route structure with HTML extensions and enhance visual appeal, I have outlined the folder structure below: Unfortunately, when acces ...

Can you please enlighten me on how to obtain the HTML for the selected area of the cursor in Tiptap?

I've successfully created a customized text editing tool using tiptap/react. My question is, how can I retrieve the html or json of a selected area when I highlight text with the cursor? For instance, if I have a custom tag 'say-as' within ...

Tips for transferring client-side data to the server-side in Angular, Node.js, and Express

Seeking a straightforward solution to a seemingly basic question. I am utilizing Angular's $http method with a GET request for a promise from a specific URL (URL_OF_INTEREST). My server runs an express script server.js capable of handling GET reques ...

Conflicting submissions

Can anyone help me with a JavaScript issue I'm facing? On a "submit" event, my code triggers an AJAX call that runs a Python script. The problem is, if one submit event is already in progress and someone else clicks the submit button, I need the AJAX ...

What is the method for specifying a .php page as the html source when using Ext.Panel?

I have a current situation where I manually set the html for an existing panel using a variable in the following way: var htmlContent = '<H1>My Html Page'; htmlContent += '[more html content]]'; var newPanel = new Ext.Panel({ ...

Just a Quick Query About Regular Expressions

I need help removing a specific part from a URL string, which looks like this: http://.....?page=1. I am aware that the code "document.URL.replace("?page=[0-9]", "")" does not work, so I am curious to learn how to accomplish this task correctly. Thank you ...