ganjan
ganjan

Reputation: 7596

Passing parameters in addition to data received from http request, to a method in angularJS

I have this method in my controller that get a json file from my API.

      $scope.get = function (code) {

          api.get(code)
              .then(onJsonPart, onError);
      };

Doing this:

      function onJsonPart(json) {

          console.log(json);
      }

I can print out the JSON I received, but I want to pass multiple variables to the onJsonPart method. Something like:

      $scope.get = function (code) {

          api.get(code)
              .then(onJsonPart(code, data), onError);
      };

Here I get ERROR: data is not defined obviously, question is how do I define the data variable with the data received.

and then have two parameters for my onJsonPart function like this:

      function onJsonPart(code, json) {

          console.log('Code: ' + code);
          console.log('json:');
          console.log(json);
      }

Upvotes: 0

Views: 39

Answers (3)

Jax
Jax

Reputation: 1843

You could do this:

$scope.get = function (code) {
      api.get(code)
          .then(function(data) {
             onJsonPart(code, data)...
          }
  };

Upvotes: 0

Florian
Florian

Reputation: 712

Try

api.get(code)
.then(function (json) {
    onJsonPart(code, data);
}, onError);

Upvotes: 0

Ben Kauer
Ben Kauer

Reputation: 596

The code below will pass codeand the API's answer res to onJsonPart():

  $scope.get = function (code) {

      api.get(code)
          .then(
              function(res) {
                  //...some place for logic
                  onJsonPart(code, res);
              },
              function (err) {
                  //...some place for logic
                  onError(err));
              }
      );
  };

Upvotes: 2

Related Questions