-1

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.

6
  • I think ng-init was build to handle expression only not sure it works well with running function. Commented Nov 12, 2016 at 13:37
  • What is prodres? Commented Nov 12, 2016 at 13:38
  • relsingle is a custom function i defined Commented Nov 12, 2016 at 13:38
  • you are not returning anything from the function. pls return a value from relsingle Commented Nov 12, 2016 at 13:40
  • What specifically is undefined? Please take a few mintes to read through How to Ask Commented Nov 12, 2016 at 13:41

2 Answers 2

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.

Sign up to request clarification or add additional context in comments.

4 Comments

still a bad practice to use ng-init for this in the first place
So what approach should i follow please explain a suitable approach with detail for this kind of problems
@charlietfl I agree that ngInit might be not the nicest approach in many cases.
@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
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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.