0

I am trying to call angular/ajax get the value from API and want setup my result in expecting results format. I try with my code but its calling twice times i don't know where i am mistaking please suggest

 $http.get('v1/res')
      .success(function (data) {

        $scope.results = [];

         angular.forEach(data.data, function(value, key){
            $scope.results.push({id: value.id});
            $scope.results.push({text: value.name});

         });

      });

//Expecting result

 $scope.results = [
    {id: 1, text: 'A'},
    {id: 2, text: 'B'},
    {id: 3, text: 'C'},
    {id: 4, text: 'D'},
    {id: 5, text: 'E'},
    {id: 6, text: 'F'},
    {id: 7, text: 'G'},
    {id: 8, text: 'H'},
  ];
3
  • What is the result that you are getting? Commented Aug 19, 2016 at 7:35
  • 1
    Maybe trying $scope.results.push({'id': value.id, 'text': value.name}); ? Commented Aug 19, 2016 at 7:35
  • The way you are doing it now will push id and text as two different object Commented Aug 19, 2016 at 7:37

2 Answers 2

1

If the result that you get from api call is the same object as you want then you can simply do as below

//assuming that data.data is an array of objects that you wish for
$scope.result = []
angular.copy(data.data, $scope.result)

otherwise

$scope.result = []
data.forEach(function(d){
    $scope.result.push({"id":d.id, "text":d.text});
});
Sign up to request clarification or add additional context in comments.

Comments

0

Isn't it enough for you getting the data you want from data.data, since it's an object with the value you want.

As you wish getting the expecting format, it should be object with id and text as its properties stored in $scope.results, but in your code, they are being stored respectively as individual object with one property. So you code should be changed like this:

angular.forEach(data.data, function(value, key){
    $scope.results.push({id: value.id, text: value.name});
});

{id: value.id, text: value.name} is the object you want to be stored in your $scope.results I think.

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.