0

I have a a controller that generates $scope.product = response.data

In my html template if type {{ product }} it shows the requested metadata in an array including the id and name. However, unless I go through the ng-repeat do ng-repeat='item in product' it won't print id and an name even though I have only one record. For example {{ product.id }} and {{ product.name }} can be displayed only as {{ item.id }} and {{ item.name }}

I have even tried $scope.product.id = response.data.id and $scope.product.name = response.data.name

Use Case:

  1. Print the product name and other information on a card
  2. Use product.id to take other actions e.g. add to cart.

1 Answer 1

2

$scope.product is an array. So it doesn't have any attribute named id or name. Its unique, first element is an object that does have those attributes. So, if you know your array has a single element, what you needs is $scope.product[0].id and $scope.product[0].name.

An array is like a box. A box doesn't become an egg if it contains a single egg. It's still an egg. And trying to fry the box won't lead to a very tasty result. You still need to get the unique egg out of the box and fry the egg.

That said, your backend should probably not return an array containing one product if the service is supposed to return a single product. It should return the product itself.

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

1 Comment

Thanks. This worked. I don't have control over the service that returns the array. That is by design. I needed to be more creative and come up with a solution similar to the one you have posted. I guess this is what happens when you get back to coding after 15 years :)

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.