0

I have the following function which takes variable description as 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;
    })
};

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

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

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;
    console.log(uri);
    $http.get(uri).success(function(data) {
      console.log(id);
      console.log(data);
      $scope.prodres = data;
    })
  };

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

console.log(description);

This gives me value undefined.

2 Answers2

1

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.

dfsq
  • 191,768
  • 25
  • 236
  • 258
  • still a bad practice to use `ng-init` for this in the first place – charlietfl Nov 12 '16 at 13:44
  • So what approach should i follow please explain a suitable approach with detail for this kind of problems – Vikas Anand Nov 12 '16 at 13:45
  • @charlietfl I agree that ngInit might be not the nicest approach in many cases. – dfsq Nov 12 '16 at 13:46
  • @VikasAnand the norm would be to make the second call within the success of the first one ... in the controller or service. The view shouldn't be used to manage controller logic – charlietfl Nov 12 '16 at 13:47
0

Well it is because it is because the array has not been evaluated in javascript.Use a call back function and store that array in a variable on the $scope scope.Then you can use it in the function

henrybbosa
  • 1,139
  • 13
  • 28