Vikas Anand Vikas Anand - 1 year ago 75
Javascript Question

Passing value in function properly in AngularJS

I have the following function which takes variable description as parameter

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

I use the following approach to pass this value in the html page


This value of prodres[0].description comes from here.
Console output

And value of prodres comes from here

$scope.prodat = function(id) {

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

when i log the value of description in console in the relsingle function.


This gives me value undefined.

Answer Source

You can't do it like this with ngInit because it runs only once and when it happence variable prodres is not yet available because it comes from async call.

What you can however do is to make ngInit execute only after the value for prodres has been resolved:

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

Because ngIf has higher priority ngInit will execute only after ngIf.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download