How to correctly pass values in AngularJS functions

Here is a function that takes a description variable as a parameter

$scope.relsingle = function(description) {
    console.log(description);
    var url = $scope.url+'/api/descrelation?limit=4&description='+description;
    $http.get(url).success(function(data) {
        console.log(data);
        $scope.apgresponse = data;
    })
};

When passing the value in the HTML page, I use the approach below

ng-init="relsingle(prodres[0].description)"

The value of prodres[0].description is obtained from https://i.sstatic.net/pErk3.png

The value of prodres is obtained from the following function

$scope.prodat = function(id) {

    var uri = $scope.url+'/api/getproduct?productid='+id;
    console.log(uri);
    $http.get(uri).success(function(data) {
      console.log(id);
      console.log(data);
      $scope.prodres = data;
    })
  };

When logging the value of description in the console within the relsingle function.

console.log(description);

It shows that the value is undefined.

Answer №1

To solve this issue, avoid using ngInit since it only runs once and the variable prodres may not be available at that moment due to its asynchronous nature.

Instead, you can ensure that ngInit is executed only after the prodres value has been resolved by using the following approach:

<div ng-if="prodres" ng-init="relsingle(prodres[0].description)">...</div>

By utilizing the ngIf directive with higher priority, ngInit will only run after ngIf.

Answer №2

The reason for this issue is that the array has not been properly evaluated in the JavaScript code. To solve this, try using a callback function to store the array in a variable within the $scope scope. Once stored, you can easily access and manipulate the array within the function.

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

Using MDBootstrap for reactjs, incorporating a modal into a table for enhanced functionality

As a newcomer to the world of React.js and Material Design Bootstrap, I am attempting to load a dataset onto a table using a mock JSON file. After some trial and error, I managed to achieve a certain level of success with this task. My goal is to include a ...

Tips for centering a div horizontally when it exceeds the width of a mobile screen

My challenge is to create a circular div element that is wider than the mobile screen and perfectly centered. This circular div needs to be an exact circle, specifically targeted for mobile screens. I've attempted to achieve this using the code in th ...

"Troubleshooting Bootstrap nav-pills' failure to update displayed content

I'm currently working on creating a dynamic navbar that updates the content based on which navigation pill is selected. For some reason, the content in my div.tab-content isn't changing as expected... Here is an example of the code I am using: ...

Tips on choosing one specific JSON object from a group and exploring its structure in Python

Looking for guidance to access a specific javascript element named SOURCE.pdp.propertyJSON and extract its attributes in a Pythonic way from a webpage filled with different script elements. Browse through the HTML source code below to get an idea and then ...

What are the steps for performing projection in TypeScript?

Looking to fill up the orders array, which consists of objects of type Order. The desired output is orders=[{id:1,qt:4},{id:2, qt:2},{id:3,qt:2}]. How can I achieve this using TypeScript? I am new to this language. export class Product { constructor(publ ...

Extending the declaration of JavaScript native methods is not possible when using TypeScript

When attempting to enhance the JS native String class by adding a new method, I encounter error TS2339. interface String { transl(): string; } String.prototype.transl = function() { // TS2339: Property 'transl' does not exist on type 'St ...

Beginner's guide to using Express: a step-by-step tutorial on making API requests from client-side JavaScript to

Currently, I am immersed in a Javascript project where I utilize the Nasa Mars Rover API and Immutable Js to creatively display images and information on my webpage. By harnessing the power of pure functions and functional programming, I maintain app state ...

Should the updater method be placed in the state or passed directly to the context?

Is it better to have this context setup like so: <MatchContext.Provider value={this.state.match}> Or should I structure it as follows in my state? match: { match: null, updateMatch: this.updateMatch }, Which approach is more eff ...

While observing a camera in motion, the particles tinted by texture display sporadic flickering on WebGL and Three.js

Check out this jsfiddle I created to illustrate an issue with particles "flickering" when colored using a texture and the camera is moving. Update: The problem occurs even when there is no animation or movement on the particles. If you notice flickering o ...

Initially, the OWL Carousel image is not displaying correctly due to incorrect sizing

I am currently working with OWL Carousel and have implemented a code that displays one image at a time, with the next image sliding in every 15 seconds. The width is set to occupy 100% of the screen and I have configured the JavaScript accordingly so that ...

How do I set up a slideshow to loop continuously?

I created a slideshow for my website using the script below, but I'm struggling to figure out how to make it repeat. I want the slideshow to go back to the first photo after reaching the last one. Can anyone help please? For reference, please check o ...

What is the best locator to use for this specific input field in the code?

Can someone help me figure out how to locate and fill in another input field in the code snippet below? '<input _ngcontent-tvt-19="" class="form-control ng-pristine ng-valid ng-touched" placeholder="You can search keywords" type="text"> I&apos ...

Issue displaying daily data on Google bar chart

Here is the link to my code on JSFiddle: https://jsfiddle.net/vbdy7fLe/1/ I am attempting to utilize a Google column chart to display multiple fields of data organized by date. However, I am facing an issue where the dates 02 Jan 2015 and 04 Jan 2015 are ...

Unable to transform node lacking a body

I am attempting to execute the sample code in the react-testing-library to test react hooks. However, it's encountering an issue on this particular line: testHook(() => ({count, increment} = useCounter({ initialCount: 2 }))) It appears to be rela ...

Retrieving the chosen item from an ng-repeat list within a datalist

Currently, I am utilizing array iteration to identify the selected option based on the ID attribute of the result. Is there a more efficient approach for this task? <input type="text" list="products" ng-model="query" /> <datalist id="products"&g ...

Callback for deletion in the Mean Stack

I have successfully implemented the delete functionality in my Mean stack application; however, I am facing an issue with updating the view after deleting an item from the JSON. On the server side of my express logic: .delete(function(req, res) { Ser ...

Use React Router to create a link that goes to the same URL but passes along unique state

Can someone help me figure out how to open the same URL using react-router Link while passing different state each time? <Link to={items.vehicleModelId === 2 ? '/ecgo-3' : items.vehicleModelId === 3 && '/ecgo-5' ...

Trying my hand at using JQuery to dynamically update the image source of a draggable element upon dropping

Essentially, I have an object being dragged with the class .dragme, a dropzone with the class .dropzone1 for it to be dropped at, and an image that I want the .dragme object to become once it has been dropped. My current code looks like this: $(".dropzon ...

Preventing page reload in Supabase with NextJS when the website loses focus and regains it

I am working with the structure in _app.js of my Next.js app. // _app.js // import ... import { createBrowserSupabaseClient } from '@supabase/auth-helpers-nextjs' import { SessionContextProvider } from '@supabase/auth-helpers-react' // ...

Having trouble capturing screenshots with PuppeteerJS?

I've encountered an issue while working with Puppeteer to capture screenshots from a provided URL. The code I have below doesn't seem to be functioning properly. It keeps showing the error message: [0] Error: Protocol error (Emulation.setDeviceM ...