0

I have an array where I would like to get an item and assign it to a variable using a function. I have the following code:

$scope.var1 = '';
$scope.var1 = '';

$scope.arr = [{
  'item1':'test1',
  'item2':'test2',
  'item3':'test3'
}];

$scope.myFunc = function(){
  $scope.var1 = $scope.arr.item1;
  $scope.var2 = $scope.arr.item1;
};

But when trying to call the function with ng-click="myFunc()" it does not work. Is this even possible to do? Or do I need to get around this another way?

Thank you in advance for any suggestions

2
  • " it does not work" what does it do? Commented Apr 25, 2018 at 14:49
  • 2
    You have an array of objects, not a simple object. In that specific array, you'd do $scope.arr[0].item1. Commented Apr 25, 2018 at 14:49

1 Answer 1

1

Your $scope.arr is an array with object(s).

So instead of

$scope.arr.item1

You have to use

$scope.arr[0].item1

Or convert your array to an object like so:

// Removed the brackets []
$scope.arr = {
    item1: 'test1',
    item2: 'test2',
    item3: 'test3'
};

Then you are able to retrieve the values like so $scope.arr.item1;

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

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.