javascriptangularjsangularjs-scopeangularjs-ng-init

Passing value in function properly in AngularJS


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.


Solution

  • 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.